package com.ldk.framework.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.util.AlipayCore;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.util.ConvertUtil;
import com.ldk.base.framework.util.DateUtil;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.base.framework.util.baidu.AddressComponentApi;
import com.ldk.base.framework.util.baidu.RouteMatrixApi;
import com.ldk.base.framework.util.baidu.routematrix.RouteMatrixRequestParms;
import com.ldk.base.framework.util.baidu.routematrix.RouteMatrixResponseParmsResult;
import com.ldk.framework.dao.IServiceTripDAO;
import com.ldk.framework.entity.Alipay;
import com.ldk.framework.entity.BCServiceOtherConfig;
import com.ldk.framework.entity.CjtRoad;
import com.ldk.framework.entity.CjtSchedul;
import com.ldk.framework.entity.Comment;
import com.ldk.framework.entity.CommentTouser;
import com.ldk.framework.entity.Companyfare;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.entity.DriverReceiveTrip;
import com.ldk.framework.entity.DriverRefuseTrip;
import com.ldk.framework.entity.KCServiceOtherConfig;
import com.ldk.framework.entity.OperateArrive;
import com.ldk.framework.entity.OperateDepart;
import com.ldk.framework.entity.OperateLogout;
import com.ldk.framework.entity.OperatePay;
import com.ldk.framework.entity.OrderCancel;
import com.ldk.framework.entity.PlatformFundFlowRecord;
import com.ldk.framework.entity.PlatformUser;
import com.ldk.framework.entity.PositionDriver;
import com.ldk.framework.entity.PositionVehicle;
import com.ldk.framework.entity.PushMessage;
import com.ldk.framework.entity.RatedPassenger;
import com.ldk.framework.entity.RechargeRecord;
import com.ldk.framework.entity.RoadLine;
import com.ldk.framework.entity.SFCServiceOtherConfig;
import com.ldk.framework.entity.ServiceConfig;
import com.ldk.framework.entity.ServiceConfigArea;
import com.ldk.framework.entity.ServicePriceRecord;
import com.ldk.framework.entity.ServiceTrip;
import com.ldk.framework.entity.ServiceTripCrews;
import com.ldk.framework.entity.Tenpay;
import com.ldk.framework.entity.TicketRelate;
import com.ldk.framework.entity.TicketUser;
import com.ldk.framework.entity.TripRefundRecord;
import com.ldk.framework.entity.TripStatusRecord;
import com.ldk.framework.entity.Unionpay;
import com.ldk.framework.entity.User;
import com.ldk.framework.entity.UserDeductRecord;
import com.ldk.framework.enums.DriverStatus;
import com.ldk.framework.enums.FareType;
import com.ldk.framework.enums.FlowInOut;
import com.ldk.framework.enums.FlowPurpose;
import com.ldk.framework.enums.OutTradeNoSuffix;
import com.ldk.framework.enums.PayType;
import com.ldk.framework.enums.PlatformUserType;
import com.ldk.framework.enums.RechargeFrom;
import com.ldk.framework.enums.RechargeType;
import com.ldk.framework.enums.ServiceCode;
import com.ldk.framework.enums.TradePayStatus;
import com.ldk.framework.enums.TripCrewStatus;
import com.ldk.framework.enums.TripRefundStatus;
import com.ldk.framework.enums.TripStatus;
import com.ldk.framework.push.CustomMsgModule;
import com.ldk.framework.push.CustomMsgType;
import com.ldk.framework.push.PushCustomMsg;
import com.ldk.framework.push.PushTargetApp;
import com.ldk.framework.service.IAlipayService;
import com.ldk.framework.service.IAreaService;
import com.ldk.framework.service.ICjtRoadService;
import com.ldk.framework.service.ICjtSchedulService;
import com.ldk.framework.service.ICommentService;
import com.ldk.framework.service.ICommentTouserService;
import com.ldk.framework.service.ICompanyfareService;
import com.ldk.framework.service.IDictService;
import com.ldk.framework.service.IDriverReceiveTripService;
import com.ldk.framework.service.IDriverRefuseTripService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IOperateArriveService;
import com.ldk.framework.service.IOperateDepartService;
import com.ldk.framework.service.IOperatePayService;
import com.ldk.framework.service.IOrderCancelService;
import com.ldk.framework.service.IOrderCreateService;
import com.ldk.framework.service.IOrderMatchService;
import com.ldk.framework.service.IPlatformFundFlowRecordService;
import com.ldk.framework.service.IPlatformUserService;
import com.ldk.framework.service.IPushMessageService;
import com.ldk.framework.service.IRatedPassengerService;
import com.ldk.framework.service.IRatedPassengercomplaintService;
import com.ldk.framework.service.IRechargeRecordService;
import com.ldk.framework.service.IRoadLineService;
import com.ldk.framework.service.IServiceConfigAreaService;
import com.ldk.framework.service.IServiceConfigService;
import com.ldk.framework.service.IServicePriceRecordService;
import com.ldk.framework.service.IServiceTripCrewsService;
import com.ldk.framework.service.IServiceTripService;
import com.ldk.framework.service.ITenpayService;
import com.ldk.framework.service.ITicketRelateService;
import com.ldk.framework.service.ITicketUserService;
import com.ldk.framework.service.ITripRefundRecordService;
import com.ldk.framework.service.ITripStatusRecordService;
import com.ldk.framework.service.IUnionpayService;
import com.ldk.framework.service.IUserDeductRecordService;
import com.ldk.framework.service.IUserService;
import com.weixin.api.WxMpService;
import com.weixin.api.WxMpServiceImpl;
import com.weixin.bean.RefundResData;

import org.apache.commons.lang.StringUtils;
import org.apache.http.util.TextUtils;
import org.apache.ibatis.annotations.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ldk.base.framework.util.SystemUtil.generateRandom;

/**
 * ServiceTripService接口实现类
 *
 * @author xiangwl
 */
@Service
public class ServiceTripService extends BaseService<ServiceTrip> implements IServiceTripService {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    protected IDictService dictService;
    @Autowired
    protected IPushMessageService pushMessageService;
    @Autowired
    protected ICommentService commentService;
    @Autowired
    protected ICommentTouserService commentTouserService;
    @Autowired
    protected IDriverService driverService;
    @Autowired
    protected IUserService userService;
    @Autowired
    protected IOrderCreateService orderCreateService;
    @Autowired
    protected IOrderMatchService orderMatchService;
    @Autowired
    protected IOrderCancelService orderCancelService;
    @Autowired
    protected IOperatePayService operatePayService;
    @Autowired
    protected IRatedPassengerService ratedPassengerService;

    @Autowired
    protected ITripStatusRecordService tripStatusRecordService;
    @Autowired
    protected IServicePriceRecordService servicePriceRecordService;
    @Autowired
    protected IUserDeductRecordService userDeductRecordService;
    @Autowired
    protected IAlipayService alipayService;
    @Autowired
    protected ITenpayService tenpayService;
    @Autowired
    protected IUnionpayService unionpayService;
    @Autowired
    protected IPlatformFundFlowRecordService platformFundFlowRecordService;
    @Autowired
    protected IOperateDepartService operateDepartService;
    @Autowired
    protected IOperateArriveService operateArriveService;
    @Autowired
    protected IServiceTripCrewsService serviceTripCrewsService;
    @Autowired
    protected IDriverRefuseTripService driverRefuseTripService;
    @Autowired
    protected IRoadLineService roadLineService;
    @Autowired
    protected IServiceConfigService serviceConfigService;
    @Autowired
    protected IServiceConfigAreaService serviceConfigAreaService;
    @Autowired
    protected
    IRechargeRecordService rechargeRecordService;
    @Autowired
    protected IPlatformUserService platformUserService;
    @Autowired
    protected IDriverReceiveTripService driverReceiveTripService;
    @Autowired
    protected ITripRefundRecordService tripRefundRecordService;
    @Autowired
    protected IAreaService areaService;
    @Autowired
    private ICompanyfareService companyfareService;
    @Autowired
    private ICjtRoadService cjtRoadService;
    @Autowired
    private ICjtSchedulService cjtSchedulService;
    @Autowired
    private ITicketRelateService ticketRelateService;
    @Autowired
    private ITicketUserService ticketUserService;

    @Autowired
    private IServiceTripDAO serviceTripDAO;
    /**
     * ===========================================================
     * 业务服务推送线程里面涉及service的访问所以要通过注解的方式来实例化
     * ===========================================================
     */
    @Autowired
    private ZXPCUserTripPushToDriverThread zxpcTripThread;
    @Autowired
    private BCUserTripPushToDriverThread bcTripTread;
    @Autowired
    private KCUserTripPushToDriverThread kcTripThread;
    @Autowired
    private SFCUserTripPushToDriverThread sfcTripThread;
    /**===========================================================
     * end
     * ===========================================================
     */

    /**
     * 平台用户ID
     */
    public static final String PLATFORM_USER_ID = "ldkd";

    @Override
    protected IBaseDAO<ServiceTrip> getBaseDao() {
        return this.serviceTripDAO;
    }


    @Override
    public Map<String, Object> estimateFee(String dbKey, String serviceCode, String carType, Long roadId, Double startLon, Double startLat, Double endLon, Double endLat, Integer crewCount, String mapKey, String areaCode) {
        //查询
        JSONObject addressComponent = AddressComponentApi.getAddressComponent(startLon.toString(), startLat.toString(), mapKey);
        if (addressComponent != null) {
            String adcode = ConvertUtil.parseString(addressComponent.getString("adcode"));
            if (!TextUtils.isEmpty(adcode)) {
                areaCode = adcode;
            }
        }
        //根据编码查询公司定价
        Companyfare querycomp = new Companyfare();
        querycomp.setAddress(areaCode);
        querycomp.setServiceCode(serviceCode);
        querycomp.setFareValue(FareType.Market.getValue());
        Companyfare companyfare = companyfareService.selectOne("", querycomp);
        if (companyfare == null) {
            //该区县没有定价,则查询市定价
            areaCode = areaCode.substring(0, 4) + "00";
            querycomp.setAddress(areaCode);
            companyfare = companyfareService.selectOne("", querycomp);
            if (companyfare == null) {
                return null;
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("areaCode", companyfare.getAddress());
        result.put("companyId", companyfare.getCompanyId());

        //两点间路线距离估算
        RouteMatrixRequestParms request = new RouteMatrixRequestParms.Builder()
                .setOrigins(String.format("%s,%s", startLat, startLon))
                .setDestinations(String.format("%s,%s", endLat, endLon))
                .setOutput("json").setTactics("11").setAk(mapKey).build();
        RouteMatrixResponseParmsResult routeMatrixResult = RouteMatrixApi.driving(request);
        // 无法估计距离
        if (routeMatrixResult == null || routeMatrixResult.getDistance().getValue() == null) {
            result.put("success", false);
            return result;
        }
        double fee = 0.0;
        //单位m
        double distance = routeMatrixResult.getDistance().getValue().doubleValue();
        double duration = routeMatrixResult.getDuration().getValue().doubleValue();
        result.put("distance", distance);
        result.put("duration", duration);
        // 转化为km
        distance = distance / 1000;
        //转为分钟
        duration = duration / 60;
        Boolean success = false;
        // 快车
        //暂时先起步价+公里和时间计费  先不计算高峰期
        if (ServiceCode.KC.getCode().equals(serviceCode)) {
            success = true;
            crewCount = Math.max(crewCount, 1);
            crewCount = Math.min(crewCount, 4);
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            // 高峰期
            if ((hour >= 20 && hour <= 24) || (hour >= 0 && hour <= 6)) {
                //kmPrice = otherConfig.getKmPriceOutTwoKmOfNight();
            }
            //起步价
            double startFare = companyfare.getStartFare();
            //起步公里数
            double startMile = companyfare.getStartMile();
            //起步分钟数
            double startMinute = companyfare.getStartMinute();

            //每公里单价
            double kmPrice = companyfare.getUnitPricePerMile();
            //每分钟单价
            double minPrice = companyfare.getUnitPricePerMinute();

            double milePrice = 0.0;
            if (distance > startMile) {
                milePrice = (distance - startMile) * kmPrice;
            }
            double timePrice = 0.0;
            if (duration > startMinute) {
                timePrice = (duration - startMinute) * minPrice;
            }
            fee = startFare + milePrice + timePrice;
        }
        // 专车
        if (ServiceCode.ZC.getCode().equals(serviceCode)) {
            success = true;
            crewCount = Math.max(crewCount, 1);
            crewCount = Math.min(crewCount, 4);
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            // 高峰期
            if ((hour >= 20 && hour <= 24) || (hour >= 0 && hour <= 6)) {
                //kmPrice = otherConfig.getKmPriceOutTwoKmOfNight();
            }
            //起步价
            double startFare = companyfare.getStartFare();
            //起步公里数
            double startMile = companyfare.getStartMile();
            //起步分钟数
            double startMinute = companyfare.getStartMinute();

            //每公里单价
            double kmPrice = companyfare.getUnitPricePerMile();
            //每分钟单价
            double minPrice = companyfare.getUnitPricePerMinute();

            double milePrice = 0.0;
            if (distance > startMile) {
                milePrice = (distance - startMile) * kmPrice;
            }
            double timePrice = 0.0;
            if (duration > startMinute) {
                timePrice = (duration - startMinute) * minPrice;
            }
            fee = startFare + milePrice + timePrice;
        }
        if (success) {
            // 费用四舍五入
            double tmp = ConvertUtil.toRoundFiexd(fee);
            result.put("fee", tmp);
            result.put("success", true);
        } else {
            result.put("fee", 0);
            result.put("success", false);
        }
        LOG.error("estimateFee::result=" + JSON.toJSONString(result));
        return result;
    }

    //计算行程的实际费用
    private double calcultePrice(String dbKey, ServiceTrip userTrip) {
        String areaCode = userTrip.getAreaCode();
        double distance = userTrip.getDistance();
        //实际的订单时间，根据起始时间相减得到

        double duration = userTrip.getDuration();
        String serviceCode = userTrip.getServiceCode();
        String usertripNo = userTrip.getTripNo();

        double fee = 0.0;
        //根据编码查询公司定价
        Companyfare querycomp = new Companyfare();
        querycomp.setAddress(areaCode);
        querycomp.setServiceCode(userTrip.getServiceCode());
        querycomp.setFareValue(FareType.Market.getValue());
        Companyfare companyfare = companyfareService.selectOne(dbKey, querycomp);
        if (companyfare == null) {
            //该区县没有定价,则查询市定价
            areaCode = areaCode.substring(0, 4) + "00";
            querycomp.setAddress(areaCode);
            companyfare = companyfareService.selectOne(dbKey, querycomp);
            if (companyfare == null) {
                return 0.0;
            }
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("areaCode", companyfare.getAddress());
        result.put("companyId", companyfare.getCompanyId());

        // 转化为km
        distance = distance / 1000;
        //转为分钟
        duration = duration / 60;
        Boolean success = false;

        //起步价
        double startFare = companyfare.getStartFare();
        //起步公里数
        double startMile = companyfare.getStartMile();
        //起步分钟数
        double startMinute = companyfare.getStartMinute();
        //每公里单价
        double kmPrice = companyfare.getUnitPricePerMile();
        //每分钟单价
        double minPrice = companyfare.getUnitPricePerMinute();

        ServicePriceRecord pricerecord = new ServicePriceRecord();
        pricerecord.setPrice(startFare);
        pricerecord.setTripNo(usertripNo);
        pricerecord.setName("起步价");
        pricerecord.setPriceType(3);
        pricerecord.setDes("含里程" + startMile + "公里，" + "含时长" + startMinute + "分钟");
        pricerecord.setUpdateTime(SystemUtil.getAllSeconds());
        servicePriceRecordService.insert(dbKey, pricerecord);

        // 快车
        //暂时先起步价+公里和时间计费  先不计算高峰期
        if (ServiceCode.KC.getCode().equals(serviceCode)) {
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            // 高峰期
            if ((hour >= 20 && hour <= 24) || (hour >= 0 && hour <= 6)) {
                //kmPrice = otherConfig.getKmPriceOutTwoKmOfNight();
            }
            double milePrice = 0.0;
            if (distance > startMile) {
                milePrice = (distance - startMile) * kmPrice;
                //包含里程费
                ServicePriceRecord pricerecord1 = new ServicePriceRecord();
                pricerecord1.setPrice(ConvertUtil.toRoundFiexd(milePrice));
                pricerecord1.setTripNo(usertripNo);
                pricerecord.setPriceType(4);
                pricerecord1.setName("里程费（" + ConvertUtil.toRoundFiexd(distance) + "公里）");
                pricerecord1.setDes("里程（" + ConvertUtil.toRoundFiexd(distance - startMile) + "公里）");
                pricerecord1.setUpdateTime(SystemUtil.getAllSeconds());
                servicePriceRecordService.insert(dbKey, pricerecord1);
            }
            double timePrice = 0.0;
            if (duration > startMinute) {
                timePrice = (duration - startMinute) * minPrice;
                //包含时长费
                ServicePriceRecord pricerecord1 = new ServicePriceRecord();
                pricerecord1.setPrice(ConvertUtil.toRoundFiexd(timePrice));
                pricerecord1.setTripNo(usertripNo);
                pricerecord.setPriceType(5);
                pricerecord1.setName("时长费（" + ConvertUtil.toRoundFiexd(duration) + "分钟）");
                pricerecord1.setDes("时长（" + ConvertUtil.toRoundFiexd(duration - startMinute) + "分钟）");
                pricerecord1.setUpdateTime(SystemUtil.getAllSeconds());
                servicePriceRecordService.insert(dbKey, pricerecord1);
            }
            fee = startFare + milePrice + timePrice;
        }
        // 专车
        if (ServiceCode.ZC.getCode().equals(serviceCode)) {
            Calendar calendar = Calendar.getInstance();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            // 高峰期
            if ((hour >= 20 && hour <= 24) || (hour >= 0 && hour <= 6)) {
                //kmPrice = otherConfig.getKmPriceOutTwoKmOfNight();
            }
            double milePrice = 0.0;
            if (distance > startMile) {
                milePrice = (distance - startMile) * kmPrice;
                //包含里程费
                ServicePriceRecord pricerecord1 = new ServicePriceRecord();
                pricerecord1.setPrice(ConvertUtil.toRoundFiexd(milePrice));
                pricerecord1.setTripNo(usertripNo);
                pricerecord.setPriceType(4);
                pricerecord1.setName("里程费（" + ConvertUtil.toRoundFiexd(distance) + "）");
                pricerecord1.setDes("里程（" + ConvertUtil.toRoundFiexd(distance - startMile) + "公里）");
                pricerecord1.setUpdateTime(SystemUtil.getAllSeconds());
                servicePriceRecordService.insert(dbKey, pricerecord1);
            }
            double timePrice = 0.0;
            if (duration > startMinute) {
                timePrice = (duration - startMinute) * minPrice;
                //包含时长费
                ServicePriceRecord pricerecord1 = new ServicePriceRecord();
                pricerecord1.setPrice(ConvertUtil.toRoundFiexd(milePrice));
                pricerecord1.setTripNo(usertripNo);
                pricerecord.setPriceType(5);
                pricerecord1.setName("时长费（" + ConvertUtil.toRoundFiexd(duration) + "）");
                pricerecord1.setDes("时长（" + ConvertUtil.toRoundFiexd(duration - startMinute) + "分钟）");
                pricerecord1.setUpdateTime(SystemUtil.getAllSeconds());
                servicePriceRecordService.insert(dbKey, pricerecord1);
            }
            fee = startFare + milePrice + timePrice;
        }
        return fee;
    }


    @Override
    public List<ServiceTrip> searchTripList(String dbKey, Map<String, Object> parms, Pageable pageable) {
        if (parms == null || parms.isEmpty())
            return null;
        try {
            return this.serviceTripDAO.searchTripList(dbKey, parms, pageable);

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    @Override
    public List<ServiceTrip> selectListIn(String dbKey, ServiceTrip query, List<String> tripNoList) {
        if (tripNoList == null || tripNoList.isEmpty())
            return null;
        try {
            return this.serviceTripDAO.selectListIn(dbKey, query, tripNoList);

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    @Override
    public int updateIn(String dbKey, ServiceTrip entity,
                        List<String> tripNoList) {
        if (entity == null || tripNoList == null || tripNoList.isEmpty())
            return 0;
        try {
            return this.serviceTripDAO.updateIn(dbKey, entity, tripNoList);

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return 0;
    }

    @Override
    public long getDayCancelCount(String dbKey, ServiceTrip query) {
        if (query == null)
            return 0;
        try {
            return this.serviceTripDAO.getDayCancelCount(dbKey, query);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return 0;
    }

    @Override
    public Boolean driverPublishTrip(final String dbKey, final ServiceTrip driverTrip) throws Exception {
        if (driverTrip == null || StringUtils.isBlank(driverTrip.getTripNo())) return false;
        int row = insert(dbKey, driverTrip);
        Boolean success = row > 0;
        if (success) {
            final String serviceCode = driverTrip.getServiceCode();
            Map<String, Object> searchParms = new HashMap<String, Object>();
            //专线拼车是通过roadId来匹配
            if (ServiceCode.ZXPC.getCode().equals(serviceCode)) {
                searchParms.put("roadId", driverTrip.getRoadId());
            } else {//其他是通过起点和目的地范围来匹配(3KM内)
                searchParms.put("startLon", driverTrip.getStartLon());
                searchParms.put("startLat", driverTrip.getStartLat());
                searchParms.put("endLon", driverTrip.getEndLon());
                searchParms.put("endLat", driverTrip.getEndLat());
                searchParms.put("scope", 60000);
            }
            searchParms.put("goTime", driverTrip.getGoTime());
            searchParms.put("carRank", driverTrip.getCarRank());
            searchParms.put("carSeats", driverTrip.getCarSeats());
            // 搜索用户发布的行程
            searchParms.put("userType", PlatformUserType.CLIENT_USER.getValue());
            // 搜索专线拼车业务的行程
            searchParms.put("serviceCode", serviceCode);
            // 搜索订单状态为支付定金状态
            int status = TripStatus.Publish.getValue();
            searchParms.put("status", status);
            CustomPageable pageable = new CustomPageable(0, 100);
            List<ServiceTrip> trips = searchTripList(dbKey, searchParms, pageable);
            if (trips != null && !trips.isEmpty()) {
                final ServiceTrip randomTrip = trips.get(0);
                //添加司机可以接的行程记录
                DriverReceiveTrip receiveTrip = new DriverReceiveTrip();
                receiveTrip.setDriverOpenId(driverTrip.getOpenId());
                receiveTrip.setTripNo(randomTrip.getTripNo());
                driverReceiveTripService.insert(dbKey, receiveTrip);

                Boolean systemAutoAssginTrip = dictService.getSystemAutoAssignTrip(dbKey);
                if (systemAutoAssginTrip) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            List<String> aliasList = new ArrayList<String>();
                            aliasList.add(driverTrip.getOpenId());
                            String toUser = driverTrip.getOpenId();
                            String moduleName = CustomMsgModule.getModuleName(serviceCode);
                            String message = String.format("%s新行程", moduleName);
                            String content = String.format("[%s]%s-%s新行程", moduleName,
                                    randomTrip.getStartLocation(), randomTrip.getEndLocation());
                            PushCustomMsg customMsg = new PushCustomMsg();
                            customMsg.setModule(serviceCode);
                            customMsg.setType(CustomMsgType.UserNewTrip.getValue());
                            customMsg.setKey(randomTrip.getTripNo());

                            PushMessage pushMessage = new PushMessage();
                            pushMessage.setContent(content);
                            pushMessage.setModule(serviceCode);
                            pushMessage.setTitle(message);
                            pushMessage.setTripNo(driverTrip.getTripNo());
                            pushMessage.setToUser(toUser);
                            pushMessage.setMessage(message);
                            pushMessage.setContent(content);
                            pushMessage.setExtras(customMsg.toJson());
                            pushMessage.setPushTime(SystemUtil.getAllSeconds());
                            pushMessage.setJumpUrl("");
                            pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Driver, customMsg, aliasList, true);
                        }
                    }).start();
                }
            }
        }
        return success;
    }

    @Override
    public Boolean driverCancelTrip(String dbKey, ServiceTrip driverTrip) throws Exception {
        if (driverTrip == null)
            return false;
        ServiceTrip driverTripEntity = new ServiceTrip();
        driverTripEntity.setTripNo(driverTrip.getTripNo());
        driverTripEntity.setStatus(TripStatus.DriverCancel.getValue());
        driverTripEntity.setCompleteTime(SystemUtil.getAllSeconds());
        updateByKey(dbKey, driverTripEntity);

        //同时添加司机行程状态记录
        TripStatusRecord statusRecord = new TripStatusRecord();
        statusRecord.setOrderNo(driverTrip.getTripNo());
        statusRecord.setStatusName(TripStatus.DriverCancel.getName());
        statusRecord.setStatusValue(TripStatus.DriverCancel.getValue());
        statusRecord.setTip(TripStatus.DriverCancel.getTip());
        statusRecord.setTime(SystemUtil.getAllSeconds());
        tripStatusRecordService.insert(dbKey, statusRecord);
        return true;
    }

    @Override
    @Transactional
    public Boolean driverCancelUserTrip(final String dbKey, final ServiceTrip driverTrip, final ServiceTrip userTrip, ServiceTripCrews tripCrew) throws Exception {
        if (driverTrip == null || userTrip == null || tripCrew == null)
            return false;
        //其他验证在外层判断，这里只做简单验证
        //获取司机
        Driver driver = driverService.getDriverByOpenId(dbKey, driverTrip.getOpenId());
        //司机不存在
        if (driver == null) return false;
        //获取司机取消次数,修改司机取消次数
        int cancelTripTimes = driver.getCancelTripTimes() == null ? 0 : driver.getCancelTripTimes();
        cancelTripTimes += 1;
        Driver driverEntity = new Driver();
        driverEntity.setDriverId(driver.getDriverId());
        driverEntity.setCancelTripTimes(cancelTripTimes);
        int row = driverService.updateByKey(dbKey, driverEntity);

        //获取司机行程未取消的乘客数
        ServiceTripCrews crewQuery = new ServiceTripCrews();
        crewQuery.setDriverTripNo(driverTrip.getTripNo());
        crewQuery.setDriverOpenId(driverTrip.getOpenId());
        crewQuery.setCanceled(false);
        long crewsCount = serviceTripCrewsService.selectCount(dbKey, crewQuery);
        //如果乘客数大于1则不设置司机当前行程的状态为取消行程，如果等于1就只有一个乘客，那么司机的行程状态也要变成取消
        if (crewsCount <= 1) {

            ServiceTrip driverTripEntity = new ServiceTrip();
            driverTripEntity.setTripNo(driverTrip.getTripNo());
            driverTripEntity.setStatus(TripStatus.DriverCancel.getValue());
            driverTripEntity.setCompleteTime(SystemUtil.getAllSeconds());
            driverTripEntity.setRemark(driverTrip.getRemark());
            updateByKey(dbKey, driverTripEntity);

            //同时添加司机行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(driverTrip.getTripNo());
            statusRecord.setStatusName(TripStatus.DriverCancel.getName());
            statusRecord.setStatusValue(TripStatus.DriverCancel.getValue());
            statusRecord.setTip(TripStatus.DriverCancel.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            tripStatusRecordService.insert(dbKey, statusRecord);
        }
        //修改用户行程状态为司机取消
        ServiceTrip userTripEntity = new ServiceTrip();
        userTripEntity.setTripNo(userTrip.getTripNo());
        userTripEntity.setStatus(TripStatus.DriverCancel.getValue());
        userTripEntity.setCompleteTime(SystemUtil.getAllSeconds());
        userTripEntity.setRemark(userTrip.getRemark());
        row = updateByKey(dbKey, userTripEntity);
        //同时添加用户行程状态记录
        TripStatusRecord statusRecord = new TripStatusRecord();
        statusRecord.setOrderNo(userTrip.getTripNo());
        statusRecord.setStatusName(TripStatus.DriverCancel.getName());
        statusRecord.setStatusValue(TripStatus.DriverCancel.getValue());
        statusRecord.setTip(TripStatus.DriverCancel.getTip());
        statusRecord.setTime(SystemUtil.getAllSeconds());
        tripStatusRecordService.insert(dbKey, statusRecord);

        //修改司机乘客为取消状态
        ServiceTripCrews tripCrewsEntity = new ServiceTripCrews();
        tripCrewsEntity.setTripCrewId(tripCrew.getTripCrewId());
        tripCrewsEntity.setCanceled(true);
        row = serviceTripCrewsService.updateByKey(dbKey, tripCrewsEntity);
        //退款给用户
        Boolean success = row > 0;
        if (success) {
            //定金已经支付成功
            if (userTrip.getDepositPayFee() != null && userTrip.getDepositPayStatus() != null && userTrip.getDepositPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue()) {
                //判断任务支付方式执行退款功能
                Boolean refundSucceed = false;
                int refundStatus = TripRefundStatus.FAILED.getValue();
                String tripNo = userTrip.getTripNo();
                //余额支付
                if (userTrip.getDepositPayId() == PayType.Balance.getId()) {
                    User user = userService.getUserByOpenId(dbKey, userTrip.getOpenId());
                    if (user != null) {
                        double depositPayFee = userTrip.getDepositPayFee() == null ? 0 : userTrip.getDepositPayFee();
                        double beforeBalance = user.getBalance();
                        double afterBalance = user.getBalance() + depositPayFee;
                        User userEntity = new User();
                        userEntity.setUserId(user.getUserId());
                        userEntity.setBalance(afterBalance);
                        int row1 = userService.updateByKey(dbKey, userEntity);
                        refundSucceed = row1 > 0;
                        //退款成功
                        if (refundSucceed) {
                            //添加用户充值记录
                            RechargeRecord record = new RechargeRecord();
                            record.setRecordNo(SystemUtil.generateRandomNo(""));
                            record.setPhoneNo(user.getOpenId());
                            record.setUserType(PlatformUserType.CLIENT_USER.getValue());
                            record.setRechargeMoney(depositPayFee);
                            record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                            record.setBeforeBalance(beforeBalance);
                            record.setAfterBalance(afterBalance);
                            record.setRechargeTime(SystemUtil.getAllSeconds());
                            record.setRechargeType(RechargeType.BalanceRefund.getValue());
                            record.setOperator("system");
                            record.setRemark("司机取消包车行程退款，余额退款充值");
                            record.setLinkTaskNo(tripNo);
                            rechargeRecordService.insert(dbKey, record);
                        }
                    }
                }//微信支付
                else if (userTrip.getDepositPayId() == PayType.Tenpay.getId()) {
                    //获取腾讯支付记录
                    String payTradeNo = userTrip.getDepositPayTradeNo();
                    Tenpay query = new Tenpay();
                    query.setTransactionId(payTradeNo);

                    Tenpay tenpay = tenpayService.selectOne(dbKey, query);
                    if (tenpay != null) {
                        WxMpService wxMpService = new WxMpServiceImpl();
                        Double totalFee = tenpay.getTotalFee() * 100;
                        int fee = totalFee.intValue();
                        RefundResData refundResData = wxMpService.refund(tenpay.getOutTradeNo(), tenpay.getTransactionId(), "", "", fee, fee, tenpay.getFeeType());

                        refundSucceed = refundResData.isResultSuccess();
                    }
                    refundStatus = refundSucceed ? TripRefundStatus.SUCCEESS.getValue() : TripRefundStatus.FAILED.getValue();

                }//支付宝支付
                else if (userTrip.getDepositPayId() == PayType.Alipay.getId()) {
                    //新的支付宝退款流程：直接调接口退款
                    String payTradeNo = userTrip.getDepositPayTradeNo();
                    Alipay query = new Alipay();
                    query.setTradeNo(payTradeNo);

                    Alipay alipay = alipayService.selectOne(dbKey, query);
                    if (alipay != null) {
                        refundSucceed = AlipayCore.refund(alipay.getOutTradeNo(), alipay.getTradeNo(), alipay.getTotalFee().floatValue(), "user cancel order refund", "", "", "", "");
                        refundStatus = refundSucceed ? TripRefundStatus.SUCCEESS.getValue() : TripRefundStatus.FAILED.getValue();
                    }
                    logger.error("userCancelTask.alipay::refundSucceed" + refundSucceed + ",refundStatus=" + refundStatus);

                }
                TripRefundRecord refundRecord = new TripRefundRecord();
                refundRecord.setTaskNo(tripNo);
                refundRecord.setRefundFee(userTrip.getDepositPayFee());
                refundRecord.setTaskPayId(userTrip.getDepositPayId());
                refundRecord.setTaskPayTradeNo(userTrip.getDepositPayTradeNo());
                refundRecord.setRefundStatus(refundStatus);
                refundRecord.setRefundTime(SystemUtil.getAllSeconds());
                //设置备注为平台资金流动用途
                refundRecord.setRemark(FlowPurpose.USER_CANCEL_TRIP_REFUND.getName());
                //添加任务退款记录
                tripRefundRecordService.insert(dbKey, refundRecord);

                //退款成功后添加平台资金流动记录,支付宝的再后台处理后在添加这个记录
                if (refundSucceed) {
                    PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
                    flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                    flowRecord.setUserUniqueId(userTrip.getOpenId());
                    flowRecord.setUserType(PlatformUserType.CLIENT_USER.getValue());
                    flowRecord.setFlowAmount(userTrip.getDepositPayFee());
                    flowRecord.setInOut(FlowInOut.OUT.getValue());
                    flowRecord.setFlowFrom("平台" + userTrip.getDepositPayName());
                    flowRecord.setFlowTo("用户" + userTrip.getDepositPayName());
                    flowRecord.setFlowMode(userTrip.getDepositPayId());
                    flowRecord.setLinkNo(tripNo);
                    flowRecord.setPurpose(FlowPurpose.USER_CANCEL_TRIP_REFUND.getName());
                    flowRecord.setRemark("用户支付定金退还给用户");

                    platformFundFlowRecordService.insert(dbKey, flowRecord);
                }
            }

            //如果支付成功，且状态为支付完成的状态，需要执行退款功能。
            if (userTrip.getPayFee() != null && userTrip.getPayStatus() != null && userTrip.getPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue()) {
                //判断任务支付方式执行退款功能
                Boolean refundSucceed = false;
                int refundStatus = TripRefundStatus.FAILED.getValue();
                String tripNo = userTrip.getTripNo();
                //余额支付
                if (userTrip.getPayId() == PayType.Balance.getId()) {
                    User user = userService.getUserByOpenId(dbKey, userTrip.getOpenId());
                    if (user != null) {
                        double beforeBalance = user.getBalance();
                        double afterBalance = user.getBalance() + userTrip.getPayFee();
                        User userEntity = new User();
                        userEntity.setUserId(user.getUserId());
                        userEntity.setBalance(afterBalance);
                        int row1 = userService.updateByKey(dbKey, userEntity);
                        refundSucceed = row1 > 0;

                        //添加用户充值记录
                        RechargeRecord record = new RechargeRecord();
                        record.setRecordNo(SystemUtil.generateRandomNo(""));
                        record.setPhoneNo(user.getOpenId());
                        record.setUserType(PlatformUserType.CLIENT_USER.getValue());
                        record.setRechargeMoney(userTrip.getPayFee());
                        record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                        record.setBeforeBalance(beforeBalance);
                        record.setAfterBalance(afterBalance);
                        record.setRechargeTime(SystemUtil.getAllSeconds());
                        record.setRechargeType(RechargeType.BalanceRefund.getValue());
                        record.setOperator("system");
                        record.setRemark("司机取消包车行程退款，余额退款充值");
                        record.setLinkTaskNo(tripNo);
                        rechargeRecordService.insert(dbKey, record);
                    }
                }//微信支付
                else if (userTrip.getPayId() == PayType.Tenpay.getId()) {
                    //获取腾讯支付记录
                    String payTradeNo = userTrip.getPayTradeNo();
                    Tenpay query = new Tenpay();
                    query.setTransactionId(payTradeNo);

                    Tenpay tenpay = tenpayService.selectOne(dbKey, query);
                    if (tenpay != null) {
                        WxMpService wxMpService = new WxMpServiceImpl();
                        Double totalFee = userTrip.getPayFee() * 100;
                        int fee = totalFee.intValue();
                        RefundResData refundResData = wxMpService.refund(tenpay.getOutTradeNo(), tenpay.getTransactionId(), "", "", fee, fee, tenpay.getFeeType());

                        refundSucceed = refundResData.isResultSuccess();
                    }
                    refundStatus = refundSucceed ? TripRefundStatus.SUCCEESS.getValue() : TripRefundStatus.FAILED.getValue();

                }//支付宝支付
                else if (userTrip.getPayId() == PayType.Alipay.getId()) {
                    //新的支付宝退款流程：直接调接口退款
                    String payTradeNo = userTrip.getPayTradeNo();
                    Alipay query = new Alipay();
                    query.setTradeNo(payTradeNo);

                    Alipay alipay = alipayService.selectOne(dbKey, query);
                    if (alipay != null) {
                        refundSucceed = AlipayCore.refund(alipay.getOutTradeNo(), alipay.getTradeNo(), alipay.getTotalFee().floatValue(), "user cancel order refund", "", "", "", "");
                        refundStatus = refundSucceed ? TripRefundStatus.SUCCEESS.getValue() : TripRefundStatus.FAILED.getValue();
                    }
                    logger.error("userCancelTask.alipay::refundSucceed" + refundSucceed + ",refundStatus=" + refundStatus);

                }
                TripRefundRecord refundRecord = new TripRefundRecord();
                refundRecord.setTaskNo(tripNo);
                refundRecord.setRefundFee(userTrip.getPayFee());
                refundRecord.setTaskPayId(userTrip.getPayId());
                refundRecord.setTaskPayTradeNo(userTrip.getPayTradeNo());
                refundRecord.setRefundStatus(refundStatus);
                refundRecord.setRefundTime(SystemUtil.getAllSeconds());
                //设置备注为平台资金流动用途
                refundRecord.setRemark(FlowPurpose.USER_CANCEL_TRIP_REFUND.getName());
                //添加任务退款记录
                tripRefundRecordService.insert(dbKey, refundRecord);

                //退款成功后添加平台资金流动记录,支付宝的再后台处理后在添加这个记录
                if (refundSucceed) {
                    PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
                    flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                    flowRecord.setUserUniqueId(userTrip.getOpenId());
                    flowRecord.setUserType(PlatformUserType.CLIENT_USER.getValue());
                    flowRecord.setFlowAmount(userTrip.getPayFee());
                    flowRecord.setInOut(FlowInOut.OUT.getValue());
                    flowRecord.setFlowFrom("平台" + userTrip.getPayName());
                    flowRecord.setFlowTo("用户" + userTrip.getPayName());
                    flowRecord.setFlowMode(userTrip.getPayId());
                    flowRecord.setLinkNo(tripNo);
                    flowRecord.setPurpose(FlowPurpose.USER_CANCEL_TRIP_REFUND.getName());
                    flowRecord.setRemark("用户支付行程费用退还给用户");

                    platformFundFlowRecordService.insert(dbKey, flowRecord);
                }

            }
        }
        if (success) {
            //推送给用户司机取消行程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String serviceCode = userTrip.getServiceCode();
                    final String openId = userTrip.getOpenId();
                    final String tripNo = userTrip.getTripNo();
                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(openId);
                    String toUser = openId;
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    String message = String.format("司机取消%s行程", moduleName);
                    String content = String.format("司机成功取消[%s]行程", moduleName);
                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.DriverCancelTrip.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(tripNo);
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                }
            }).start();
        }
        if (row > 0) {
            try {
                OrderCancel orderCancel = new OrderCancel();
                orderCancel.setCompanyId("5201HDCX8779");
                orderCancel.setAddress(520100L);
                orderCancel.setOrderId(userTrip.getTripNo());
                Date start = new Date(userTrip.getCreateTime() * 1000L);
                orderCancel.setOrderTime(Long.parseLong(DateUtil.DatetoString(start, "yyyyMMddHHmmss")));
                orderCancel.setCancelTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                orderCancel.setOperator("2");
                orderCancel.setCancelTypeCode("2");
                orderCancel.setCancelReason("");
                orderCancel.setCancelTime2(0L);
                orderCancelService.insertUpper("", orderCancel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return row > 0;
    }

    @Override
    public Boolean pushTripToDriver(String dbKey, ServiceTrip trip) throws Exception {
        Boolean systemAutoAssignTrip = dictService.getSystemAutoAssignTrip(dbKey);
        //系统自动派单开启
        if (systemAutoAssignTrip) {
            final String serviceCode = trip.getServiceCode();

            logger.error("ycs serviceCode=" + serviceCode);

            if (ServiceCode.BC.getCode().equals(serviceCode)) {
                bcTripTread.setUserTrip(trip);
                new Thread(bcTripTread).start();
            } else if (ServiceCode.ZC.getCode().equals(serviceCode)) {
                zxpcTripThread.setUserTrip(trip);
                new Thread(kcTripThread).start();
            } else if (ServiceCode.KC.getCode().equals(serviceCode)) {
                kcTripThread.setUserTrip(trip);
                new Thread(kcTripThread).start();

            } else if (ServiceCode.SFC.getCode().equals(serviceCode)) {
                sfcTripThread.setUserTrip(trip);
                new Thread(sfcTripThread).start();
            }
        }
        return true;
    }


    @Override
    @Transactional
    public synchronized Boolean payTripDeposit(final String dbKey, final String outTradeNo, String payTradeNo, Tenpay tenpay, Alipay alipay) throws Exception {
        if (StringUtils.isBlank(outTradeNo))
            return false;
        final String tripNo = outTradeNo.replace(OutTradeNoSuffix.Deposit.getSuffix(), "");
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setTripNo(tripNo);
        final ServiceTrip trip = selectOne(dbKey, tripQuery);
        if (trip == null)
            return false;
        //定金支付状态不对
        if (trip.getDepositPayStatus() == null ||
                trip.getDepositPayStatus() != TradePayStatus.WAIT_BUYER_PAY.getValue())
            return false;

        User user = userService.getUserByOpenId(dbKey, trip.getOpenId());
        //用户不存在
        if (user == null)
            return false;
        //修改用户订单
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(tripNo);
        tripEntity.setDepositPayStatus(TradePayStatus.TRADE_SUCCESS.getValue());
        tripEntity.setDepositPayTradeNo(payTradeNo);
        tripEntity.setDepositPayTime(SystemUtil.getAllSeconds());
        //tripEntity.setStatus(TripStatus.DepositPayed.getValue());

        //修改司机订单

        int row = updateByKey(dbKey, tripEntity);
        if (row > 0) {
            //添加行程状态
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.Publish.getName());
            statusRecord.setStatusValue(TripStatus.Publish.getValue());
            statusRecord.setTip(TripStatus.Publish.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());

            row = tripStatusRecordService.insert(dbKey, statusRecord);

            int payId = trip.getDepositPayId();
            String payName = PayType.getPayName(payId);
            double depositFee = trip.getDepositPayFee() == null ? 0 : trip.getDepositPayFee();
            //余额支付，扣用户余额
            if (payId == PayType.Balance.getId()) {
                double beforeBalance = user.getBalance();
                double afterBalance = beforeBalance - depositFee;
                User userEntity = new User();
                userEntity.setUserId(user.getUserId());
                userEntity.setBalance(afterBalance);
                //修改用户余额
                userService.updateByKey(dbKey, userEntity);
                //用户扣费记录
                UserDeductRecord record = new UserDeductRecord();
                record.setRecordNo(SystemUtil.generateRandomNo(""));
                record.setOpenId(trip.getOpenId());
                record.setBeforeBalance(beforeBalance);
                record.setAfterBalance(afterBalance);
                record.setDeductFee(depositFee);
                record.setOrderNo(tripNo);
                record.setRemark(FlowPurpose.USER_ORDER_PAY.getName());
                record.setDeductTime(SystemUtil.getAllSeconds());
                //增加用户扣费记录
                userDeductRecordService.insert(dbKey, record);
            }//支付宝支付
            else if (payId == PayType.Alipay.getId() && alipay != null) {
                Alipay query = new Alipay();
                query.setOutTradeNo(outTradeNo);

                Alipay existObj = alipayService.selectOne(dbKey, query);
                if (existObj != null) {
                    alipay.setPayId(existObj.getPayId());
                    alipayService.updateByKey(dbKey, alipay);
                } else {
                    alipayService.insert(dbKey, alipay);
                }
            }//微信支付
            else if (payId == PayType.Tenpay.getId() && tenpay != null) {
                Tenpay query = new Tenpay();
                query.setOutTradeNo(outTradeNo);//商户行程编号

                Tenpay existObj = tenpayService.selectOne(dbKey, query);
                if (existObj != null) {
                    tenpay.setPayId(existObj.getPayId());
                    tenpayService.updateByKey(dbKey, tenpay);
                } else {
                    tenpayService.insert(dbKey, tenpay);
                }
            }
            //2添加平台流动资金记录
            PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
            flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
            flowRecord.setUserUniqueId(trip.getOpenId());
            flowRecord.setUserType(PlatformUserType.CLIENT_USER.getValue());
            flowRecord.setFlowAmount(depositFee);

            //ycs 2019-05-25
            //flowRecord.setInOut(FlowInOut.IN.getValue());
            flowRecord.setInOut(FlowInOut.OUT.getValue());

            flowRecord.setFlowFrom("用户" + payName);
            flowRecord.setFlowTo("平台" + payName);
            flowRecord.setFlowMode(payId);
            flowRecord.setLinkNo(tripNo);
            flowRecord.setPurpose(FlowPurpose.USER_ORDER_PAY.getName());
            row = platformFundFlowRecordService.insert(dbKey, flowRecord);
        }
        //不需要推送
        if (row > 0) {
            //推送给用户
            new Thread(new Runnable() {

                @Override
                public void run() {
                    String serviceCode = trip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(trip.getOpenId());
                    String toUser = trip.getOpenId();
                    String message = String.format("用户支付%s行程定金", moduleName);
                    String content = String.format("用户已成功支付[%s]行程定金,行程单号为：%s", moduleName, tripNo);
                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.UserDepositPayed.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(trip.getTripNo());
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);

                }
            }).start();

            Boolean systemAutoAssignTrip = dictService.getSystemAutoAssignTrip(dbKey);
            //系统自动派单开启
            if (systemAutoAssignTrip) {
                final String serviceCode = trip.getServiceCode();
                if (ServiceCode.BC.getCode().equals(serviceCode)) {
                    bcTripTread.setUserTrip(trip);
                    new Thread(bcTripTread).start();
                } else if (ServiceCode.ZC.getCode().equals(serviceCode)) {
                    zxpcTripThread.setUserTrip(trip);
                    new Thread(kcTripThread).start();
                } else if (ServiceCode.KC.getCode().equals(serviceCode)) {
                    kcTripThread.setUserTrip(trip);
                    new Thread(kcTripThread).start();

                } else if (ServiceCode.SFC.getCode().equals(serviceCode)) {
                    sfcTripThread.setUserTrip(trip);
                    new Thread(sfcTripThread).start();
                }
            }
        }
        return row > 0;
    }

    @Override
    @Transactional
    public synchronized Boolean payTrip(final String dbKey, final String outTradeNo, String payTradeNo,
                                        Tenpay tenpay, Alipay alipay, Unionpay unionpay) throws Exception {
        if (StringUtils.isBlank(outTradeNo))
            return false;
        final String tripNo = outTradeNo.replace(OutTradeNoSuffix.Balance.getSuffix(), "");
        logger.error("idinfo:tripNo" + tripNo);
        ServiceTrip tripQuery = new ServiceTrip();
        tripQuery.setTripNo(tripNo);
        final ServiceTrip trip = selectOne(dbKey, tripQuery);
        if (trip == null)
            return false;
        //支付状态不对
        if (trip.getPayStatus() != null && trip.getPayStatus() != TradePayStatus.WAIT_BUYER_PAY.getValue())
            return false;
        logger.error("idinfo:tripNo" + "支付1");
        User user = userService.getUserByOpenId(dbKey, trip.getOpenId());
        //用户不存在
        if (user == null)
            return false;
        final String openId = trip.getOpenId();
        Long payTime=SystemUtil.getAllSeconds();
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(tripNo);
        tripEntity.setPayStatus(TradePayStatus.TRADE_SUCCESS.getValue());
        tripEntity.setPayTradeNo(payTradeNo);
        tripEntity.setPayTime(payTime);
        tripEntity.setStatus(TripStatus.Payed.getValue());
        int payId = trip.getPayId();
        String payName = PayType.getPayName(payId);
        tripEntity.setPayId(payId);
        tripEntity.setPayName(payName);

        int row = updateByKey(dbKey, tripEntity);
        if (row > 0) {
            //如果为城际通，查询司机订单，修改座位数
            if (trip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
                ServiceTrip querydriver = new ServiceTrip();
                querydriver.setDriverOpenId(trip.getDriverOpenId());
                querydriver.setUserType(PlatformUserType.DRIVER_USER.getValue());
                ServiceTrip driverserviceTrip = selectOne(dbKey, querydriver);
                if (driverserviceTrip != null) {
                    ServiceTrip serviceTrip = new ServiceTrip();
                    serviceTrip.setTripNo(driverserviceTrip.getTripNo());
                    serviceTrip.setCrewCount(driverserviceTrip.getCrewCount() + trip.getCrewCount());
                    updateByKey(dbKey, serviceTrip);
                    //排班记录中修改人数
                    CjtSchedul schedulquery = new CjtSchedul();
                    schedulquery.setId(driverserviceTrip.getSchedulId());
                    CjtSchedul cjtSchedul = cjtSchedulService.selectOne(dbKey, schedulquery);
                    if (cjtSchedul != null) {
                        CjtSchedul cjtSchedul1 = new CjtSchedul();
                        cjtSchedul1.setId(cjtSchedul.getId());
                        cjtSchedul1.setHaveSeat(cjtSchedul.getHaveSeat() - trip.getCrewCount());
                        cjtSchedulService.updateByKey(dbKey, cjtSchedul1);
                    }
                }
            }

            //logger.error("idinfo:tripNo" + "支付2");
            //添加行程状态
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.Payed.getName());
            statusRecord.setStatusValue(TripStatus.Payed.getValue());
            statusRecord.setTip(TripStatus.Payed.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());

            row = tripStatusRecordService.insert(dbKey, statusRecord);
            //查询乘客记录
            ServiceTripCrews crewsQuery = new ServiceTripCrews();
            crewsQuery.setCrewTripNo(tripNo);
            crewsQuery.setCrewOpenId(openId);

            ServiceTripCrews tripCrews = serviceTripCrewsService.selectOne(dbKey, crewsQuery);
            //如果存在修改支付状态
            if (tripCrews != null) {
                crewsQuery = new ServiceTripCrews();
                crewsQuery.setTripCrewId(tripCrews.getTripCrewId());
                crewsQuery.setPayStatus(true);
                //修改支付状态为已支付
                serviceTripCrewsService.updateByKey(dbKey, crewsQuery);

                //修改司机订单号
                ServiceTrip query1 = new ServiceTrip();
                query1.setTripNo(tripCrews.getDriverTripNo());
                ServiceTrip driverServiceTrip = selectOne("", query1);
                if (driverServiceTrip != null) {
                    driverServiceTrip.setPayStatus(tripEntity.getPayStatus());
                    driverServiceTrip.setPayTradeNo(tripEntity.getPayTradeNo());
                    driverServiceTrip.setPayTime(tripEntity.getPayTime());
                    driverServiceTrip.setStatus(tripEntity.getStatus());
                    driverServiceTrip.setPayId(tripEntity.getPayId());
                    driverServiceTrip.setPayName(tripEntity.getPayName());
                    updateByKey("", driverServiceTrip);
                }
            }

            //int payId = trip.getPayId();
            //String payName = PayType.getPayName(payId);
            double payFee = trip.getPayFee() == null ? 0 : trip.getPayFee();
            //余额支付，扣用户余额
            if (payId == PayType.Balance.getId()) {
                double beforeBalance = user.getBalance();
                double afterBalance = beforeBalance - payFee;
                User userEntity = new User();
                userEntity.setUserId(user.getUserId());
                userEntity.setBalance(afterBalance);
                //修改用户余额
                userService.updateByKey(dbKey, userEntity);
                //用户扣费记录
                UserDeductRecord record = new UserDeductRecord();
                record.setRecordNo(SystemUtil.generateRandomNo(""));
                record.setOpenId(trip.getOpenId());
                record.setBeforeBalance(beforeBalance);
                record.setAfterBalance(afterBalance);
                record.setDeductFee(payFee);
                record.setOrderNo(tripNo);
                record.setRemark(FlowPurpose.USER_ORDER_PAY.getName());
                record.setDeductTime(SystemUtil.getAllSeconds());
                //增加用户扣费记录
                userDeductRecordService.insert(dbKey, record);
            }//支付宝支付
            else if (payId == PayType.Alipay.getId() && alipay != null) {
                Alipay query = new Alipay();
                query.setOutTradeNo(outTradeNo);

                Alipay existObj = alipayService.selectOne(dbKey, query);
                if (existObj != null) {
                    alipay.setPayId(existObj.getPayId());
                    alipayService.updateByKey(dbKey, alipay);
                } else {
                    alipayService.insert(dbKey, alipay);
                }
            }//微信支付
            else if (payId == PayType.Tenpay.getId() && tenpay != null) {
                Tenpay query = new Tenpay();
                query.setOutTradeNo(outTradeNo);//商户行程编号

                Tenpay existObj = tenpayService.selectOne(dbKey, query);
                if (existObj != null) {
                    tenpay.setPayId(existObj.getPayId());
                    tenpayService.updateByKey(dbKey, tenpay);
                } else {
                    tenpayService.insert(dbKey, tenpay);
                }
            }//银联支付
            else if (payId == PayType.UnionPay.getId() && unionpay != null) {
                Unionpay query = new Unionpay();
                query.setOrderId(outTradeNo);//商户行程编号

                Unionpay existObj = unionpayService.selectOne(dbKey, query);
                if (existObj != null) {
                    unionpay.setPayId(existObj.getPayId());
                    unionpayService.updateByKey(dbKey, unionpay);
                } else {
                    unionpayService.insert(dbKey, unionpay);
                }
            }

            //2 添加平台流动资金记录
            PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
            flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
            flowRecord.setUserUniqueId(trip.getOpenId());
            flowRecord.setUserType(PlatformUserType.CLIENT_USER.getValue());
            flowRecord.setFlowAmount(payFee);

            //ycs 2019-05-25
            //flowRecord.setInOut(FlowInOut.IN.getValue());
            flowRecord.setInOut(FlowInOut.OUT.getValue());

            flowRecord.setFlowFrom("用户" + payName);
            flowRecord.setFlowTo("平台" + payName);
            flowRecord.setFlowMode(payId);
            flowRecord.setLinkNo(tripNo);
            flowRecord.setPurpose(FlowPurpose.USER_ORDER_PAY.getName());
            row = platformFundFlowRecordService.insert(dbKey, flowRecord);


            //支付成功后，快车和专车直接接受行程
            if (trip.getServiceCode().equals(ServiceCode.KC.getCode())
                    || trip.getServiceCode().equals(ServiceCode.ZC.getCode())) {
                paySuccessCompleteTrip("", trip);
            }

        }
        //如果行程已被司机接单，推送通知司机用户已支付行程
        if (row > 0 && trip.getStatus() >= TripStatus.Accept.getValue()) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    String serviceCode = trip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(trip.getDriverOpenId());
                    String toUser = trip.getDriverOpenId();
                    String message = String.format("用户支付%s行程", moduleName);
                    String content = String.format("用户已成功支付[%s]行程,行程单号为：%s", moduleName, tripNo);
                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.UserFeePayed.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(trip.getTripNo());
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Driver, customMsg, aliasList, true);

                }
            }).start();
        }
        if (row > 0) {
            Driver driver = driverService.getDriverByOpenId("", trip.getDriverOpenId());
            if (driver != null) {
                OperatePay operatePay = new OperatePay();
                operatePay.setCompanyId("5201HDCX8779");
                operatePay.setOrderId(trip.getTripNo());
                operatePay.setOnArea(520100L);
                operatePay.setDriverName(driver.getTrueName());
                operatePay.setLicenseId(driver.getIdCard());
                operatePay.setFareType("HDCX002");
                operatePay.setVehicleNo(driver.getCarNo());
                Date date = new Date(trip.getGoTime() * 1000);
                operatePay.setBookDepTime(Long.parseLong(DateUtil.DatetoString(date, "yyyyMMddHHmmss")));
                operatePay.setDepLongitude(trip.getStartLon());
                operatePay.setDepLatitude(trip.getStartLat());
                operatePay.setDepArea(trip.getStartLocation());
                Date date1 = new Date(trip.getRealGoTime() * 1000);
                operatePay.setDepTime(Long.parseLong(DateUtil.DatetoString(date1, "yyyyMMddHHmmss")));
                operatePay.setDestLongitude(trip.getEndLon());
                operatePay.setDestLatitude(trip.getEndLat());
                operatePay.setDestArea(trip.getEndLocation());
                operatePay.setDestTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                //operatePay.setBookModel("");
                // operatePay.setModel("");
                operatePay.setDriveMile(trip.getDistance() / 1000);
                operatePay.setDriveTime(trip.getDuration());
                OperateDepart query1 = new OperateDepart();
                query1.setOrderId(trip.getTripNo());
                OperateDepart operateDepart = operateDepartService.selectOne("", query1);
                if(operateDepart!=null){
                    operatePay.setWaitMile(operateDepart.getWaitMile());
                }
                operatePay.setFactPrice(trip.getPayFee());
                operatePay.setPrice(trip.getPayFee());
                operatePay.setCashPrice(0.0D);
                operatePay.setLineName(PayType.getPayName(trip.getPayId()));
                operatePay.setLinePrice(trip.getPayFee());
                operatePay.setPosName("");
                operatePay.setPosPrice(0.0D);
                operatePay.setBenfitPrice(0.0D);
                operatePay.setBookTip(0.0D);
                operatePay.setPassengerTip(0.0D);
                operatePay.setPeakUpPrice(0.0D);
                operatePay.setNightUpPrice(0.0D);
                operatePay.setFarUpPrice(0.0D);
                operatePay.setOtherUpPrice(0.0D);
                operatePay.setPayState("1");
                //Date datepay = new Date(trip.getPayTime() * 1000);
                operatePay.setPayTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                //Date datecompate = new Date(trip.getCompleteTime() * 1000);
                operatePay.setOrderMatchTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                operatePay.setInvoiceStatus("0");
                operatePay.setOrderMatchTime2(0L);
                operatePayService.insertUpper("", operatePay);
            }
        }
        return row > 0;
    }

    @Override
    @Transactional
    public Boolean driverRefuse(String dbKey, String driverOpenId, final ServiceTrip userTrip, String reason) throws Exception {
        if (userTrip == null) return false;
        ServiceTrip entity = new ServiceTrip();
        entity.setTripNo(userTrip.getTripNo());
        entity.setStatus(TripStatus.Refuse.getValue());

        int row = updateByKey(dbKey, entity);
        if (row > 0) {
            //添加司机拒绝订单记录
            DriverRefuseTrip record = new DriverRefuseTrip();
            record.setDriverOpenId(driverOpenId);
            record.setServiceCode(userTrip.getServiceCode());
            record.setTripNo(userTrip.getTripNo());
            record.setReason(reason);
            record.setStatus(1);//申请提交
            record.setRefuseTime(SystemUtil.getAllSeconds());

            driverRefuseTripService.insert("", record);
        }

        return row > 0;
    }

    @Override
    @Transactional
    public Boolean driverSureGo(final String dbKey, final ServiceTrip trip, final List<ServiceTripCrews> crews) throws Exception {
        if (trip == null || crews == null || crews.isEmpty()) return false;
        //司机行程为出发
        ServiceTrip entity = new ServiceTrip();
        entity.setTripNo(trip.getTripNo());
        entity.setStatus(TripStatus.Go.getValue());
        entity.setRealGoTime(SystemUtil.getAllSeconds());
        int row = updateByKey(dbKey, entity);
        if (row > 0) {
            //添加司机行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(trip.getTripNo());
            statusRecord.setStatusName(TripStatus.Go.getName());
            statusRecord.setStatusValue(TripStatus.Go.getValue());
            statusRecord.setTip(TripStatus.Go.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            row = tripStatusRecordService.insert(dbKey, statusRecord);

            //修改司机状态为working
            String driverOpenId = trip.getDriverOpenId();
            Driver driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
            Driver driverEntity = new Driver();
            driverEntity.setDriverId(driver.getDriverId());
            driverEntity.setStatus(DriverStatus.Working.getValue());
            driverService.updateByKey(dbKey, driverEntity);
        }
        final List<String> tripNoList = new ArrayList<String>();
        if (crews != null && !crews.isEmpty()) {
            for (ServiceTripCrews item : crews) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        if (tripNoList != null && !tripNoList.isEmpty()) {
            ServiceTrip userTripEntity = new ServiceTrip();
            userTripEntity.setStatus(TripStatus.Go.getValue());
            userTripEntity.setRealGoTime(SystemUtil.getAllSeconds());
            //修改司机行程下用户行程状态也为出发状态
            updateIn(dbKey, userTripEntity, tripNoList);
            //同时添加用户行程状态记录
            for (String tripNo : tripNoList) {
                TripStatusRecord statusRecord = new TripStatusRecord();
                statusRecord.setOrderNo(tripNo);
                statusRecord.setStatusName(TripStatus.Go.getName());
                statusRecord.setStatusValue(TripStatus.Go.getValue());
                statusRecord.setTip(TripStatus.Go.getTip());
                statusRecord.setTime(SystemUtil.getAllSeconds());
                tripStatusRecordService.insert(dbKey, statusRecord);
            }
        }
        if (row > 0) {
            //推送通知所有乘客司机行程已发车
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (ServiceTripCrews item : crews) {
                        String tripNo = item.getCrewTripNo();
                        String toUser = "";
                        String serviceCode = trip.getServiceCode();
                        String moduleName = CustomMsgModule.getModuleName(serviceCode);
                        String message = String.format("司机%s行程已出发", moduleName);
                        String content = String.format("司机%s行程已出发,行程号为：%s", moduleName, tripNo);

                        List<String> aliasList = new ArrayList<String>();
                        aliasList.add(item.getCrewOpenId());
                        toUser = item.getCrewOpenId();

                        PushCustomMsg customMsg = new PushCustomMsg();
                        customMsg.setModule(serviceCode);
                        customMsg.setType(CustomMsgType.TripGo.getValue());
                        customMsg.setKey(tripNo);

                        PushMessage pushMessage = new PushMessage();
                        pushMessage.setContent(content);
                        pushMessage.setModule(serviceCode);
                        pushMessage.setTitle(message);
                        pushMessage.setTripNo(tripNo);
                        pushMessage.setToUser(toUser);
                        pushMessage.setMessage(message);
                        pushMessage.setContent(content);
                        pushMessage.setExtras(customMsg.toJson());
                        pushMessage.setPushTime(SystemUtil.getAllSeconds());
                        pushMessage.setJumpUrl("");

                        pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                    }
                }
            }).start();
        }
        return row > 0;
    }

    @Override
    public Boolean driverArriveStartAdd(final String dbKey, final ServiceTrip trip, final List<ServiceTripCrews> crews) throws Exception {
        if (trip == null || crews == null || crews.isEmpty()) return false;
        //司机行程为出发
        ServiceTrip entity = new ServiceTrip();
        entity.setTripNo(trip.getTripNo());
        entity.setStatus(TripStatus.WaitingPerson.getValue());
        int row = updateByKey(dbKey, entity);
        if (row > 0) {
            //添加司机行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(trip.getTripNo());
            statusRecord.setStatusName(TripStatus.WaitingPerson.getName());
            statusRecord.setStatusValue(TripStatus.WaitingPerson.getValue());
            statusRecord.setTip(TripStatus.WaitingPerson.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            row = tripStatusRecordService.insert(dbKey, statusRecord);
        }
        final List<String> tripNoList = new ArrayList<String>();
        if (crews != null && !crews.isEmpty()) {
            for (ServiceTripCrews item : crews) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        if (tripNoList != null && !tripNoList.isEmpty()) {
            ServiceTrip userTripEntity = new ServiceTrip();
            userTripEntity.setStatus(TripStatus.WaitingPerson.getValue());
            //修改司机行程下用户行程状态也为出发状态
            updateIn(dbKey, userTripEntity, tripNoList);
            //同时添加用户行程状态记录
            for (String tripNo : tripNoList) {
                TripStatusRecord statusRecord = new TripStatusRecord();
                statusRecord.setOrderNo(tripNo);
                statusRecord.setStatusName(TripStatus.WaitingPerson.getName());
                statusRecord.setStatusValue(TripStatus.WaitingPerson.getValue());
                statusRecord.setTip(TripStatus.WaitingPerson.getTip());
                statusRecord.setTime(SystemUtil.getAllSeconds());
                tripStatusRecordService.insert(dbKey, statusRecord);
            }
        }
        if (row > 0) {
            //推送通知所有乘客司机行程已到达上车地点
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (ServiceTripCrews item : crews) {
                        String tripNo = item.getCrewTripNo();
                        String toUser = "";
                        String serviceCode = trip.getServiceCode();
                        String moduleName = CustomMsgModule.getModuleName(serviceCode);
                        String message = String.format("司机%s行程已到达上车地点", moduleName);
                        String content = String.format("司机%s行程已到达上车地点,行程号为：%s", moduleName, tripNo);

                        List<String> aliasList = new ArrayList<String>();
                        aliasList.add(item.getCrewOpenId());
                        toUser = item.getCrewOpenId();

                        PushCustomMsg customMsg = new PushCustomMsg();
                        customMsg.setModule(serviceCode);
                        customMsg.setType(CustomMsgType.TripDriverArrive.getValue());
                        customMsg.setKey(tripNo);

                        PushMessage pushMessage = new PushMessage();
                        pushMessage.setContent(content);
                        pushMessage.setModule(serviceCode);
                        pushMessage.setTitle(message);
                        pushMessage.setTripNo(tripNo);
                        pushMessage.setToUser(toUser);
                        pushMessage.setMessage(message);
                        pushMessage.setContent(content);
                        pushMessage.setExtras(customMsg.toJson());
                        pushMessage.setPushTime(SystemUtil.getAllSeconds());
                        pushMessage.setJumpUrl("");

                        pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                    }
                }
            }).start();
        }
        return row > 0;
    }


    @Override
    @Transactional
    public Boolean driverSureUserOnCar(final String dbKey, final ServiceTrip driverTrip, final ServiceTrip userTrip, final List<ServiceTripCrews> crews) throws Exception {
        if (driverTrip == null)
            return false;
        //修改行程订单的状态为用户上车
        //修改用户订单状态为上车
        final String tripNo = driverTrip.getTripNo();
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(tripNo);
        tripEntity.setStatus(TripStatus.OnTheCar.getValue());

        int row = updateByKey(dbKey, tripEntity);
        if (row > 0) {
            //添加订单状态
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.OnTheCar.getName());
            statusRecord.setStatusValue(TripStatus.OnTheCar.getValue());
            statusRecord.setTip(TripStatus.OnTheCar.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());

            row = tripStatusRecordService.insert(dbKey, statusRecord);
        }
        final List<String> tripNoList = new ArrayList<String>();
        if (crews != null && !crews.isEmpty()) {
            for (ServiceTripCrews item : crews) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        if (tripNoList != null && !tripNoList.isEmpty()) {
            ServiceTrip userTripEntity = new ServiceTrip();
            userTripEntity.setStatus(TripStatus.OnTheCar.getValue());
            //修改司机行程下用户行程状态也为出发状态
            updateIn(dbKey, userTripEntity, tripNoList);
            //同时添加用户行程状态记录
            for (String tripNo1 : tripNoList) {
                TripStatusRecord statusRecord = new TripStatusRecord();
                statusRecord.setOrderNo(tripNo1);
                statusRecord.setStatusName(TripStatus.OnTheCar.getName());
                statusRecord.setStatusValue(TripStatus.OnTheCar.getValue());
                statusRecord.setTip(TripStatus.OnTheCar.getTip());
                statusRecord.setTime(SystemUtil.getAllSeconds());
                tripStatusRecordService.insert(dbKey, statusRecord);
            }
        }
        /*if (row > 0) {
            //如为城际通，则需要修改乘客的订单状态
            if (driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
                ServiceTrip crewsQuery = new ServiceTrip();
                crewsQuery.setSchedulId(driverTrip.getSchedulId());
                crewsQuery.setDriverOpenId(driverTrip.getDriverOpenId());
                List<ServiceTrip> crews = selectList("", crewsQuery);
                if (crews != null && crews.size() > 0) {
                    //添加乘客行程状态
                    for (ServiceTrip serviceTrip : crews) {
                        ServiceTrip userTripEntity = new ServiceTrip();
                        userTripEntity.setTripNo(serviceTrip.getTripNo());
                        userTripEntity.setStatus(TripStatus.OnTheCar.getValue());
                        updateByKey(dbKey, userTripEntity);

                        TripStatusRecord statusRecord = new TripStatusRecord();
                        statusRecord.setOrderNo(serviceTrip.getTripNo());
                        statusRecord.setStatusName(TripStatus.OnTheCar.getName());
                        statusRecord.setStatusValue(TripStatus.OnTheCar.getValue());
                        statusRecord.setTip(TripStatus.OnTheCar.getTip());
                        statusRecord.setTime(SystemUtil.getAllSeconds());
                        tripStatusRecordService.insert(dbKey, statusRecord);
                    }
                }
            }
        }*/
        if (row > 0) {
            //推送通知所有乘客--确认用户上车
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String tripNo = userTrip.getTripNo();
                    String toUser = "";
                    String serviceCode = userTrip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    String message = String.format("司机%s行程确认用户上车", moduleName);
                    String content = String.format("司机%s行程确认用户上车,行程号为：%s", moduleName, tripNo);

                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(userTrip.getOpenId());
                    toUser = userTrip.getOpenId();

                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.TripCrewUpCar.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(tripNo);
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                }
            }).start();
        }
        if (row > 0) {
            Driver driver = driverService.getDriverByOpenId("", userTrip.getDriverOpenId());
            if (driver != null) {
                OperateDepart operateDepart = new OperateDepart();
                operateDepart.setCompanyId("5201HDCX8779");
                operateDepart.setOrderId(userTrip.getTripNo());
                operateDepart.setLicenseId(driver.getIdCard());
                operateDepart.setFareType("HDCX002");
                operateDepart.setVehicleNo(driver.getCarNo());
                operateDepart.setDepLongitude(driver.getLon());
                operateDepart.setDepLatitude(driver.getLat());
                operateDepart.setEncrypt(3L);
                operateDepart.setDepTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                operateDepart.setDepTime2(0L);
                Double mile = generateRandom(5000) * 1.0 / 1000.0;
                operateDepart.setWaitMile(mile);
                operateDepart.setWaitTime(mile * generateRandom(5) * 80);
                operateDepartService.insertUpper("", operateDepart);
            }
        }
        return row > 0;
    }

    /**
     * 司机确认用户下车
     *
     * @param dbKey
     * @param driverTrip 司机订单
     * @param userTrip   用户行程
     * @return
     * @throws Exception
     */
    @Override
    public Boolean driverSureUserOffCar(final String dbKey, ServiceTrip driverTrip, final ServiceTrip userTrip, List<ServiceTripCrews> crews) throws Exception {
        if (driverTrip == null)
            return false;
        //修改行程订单的状态为用户上车
        //修改用户订单状态为上车
        final String tripNo = driverTrip.getTripNo();
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(tripNo);
        tripEntity.setStatus(TripStatus.OFFTheCar.getValue());

        int row = updateByKey(dbKey, tripEntity);
        if (row > 0) {
            //添加订单状态
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.OFFTheCar.getName());
            statusRecord.setStatusValue(TripStatus.OFFTheCar.getValue());
            statusRecord.setTip(TripStatus.OFFTheCar.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            row = tripStatusRecordService.insert(dbKey, statusRecord);
        }
        final List<String> tripNoList = new ArrayList<String>();
        if (crews != null && !crews.isEmpty()) {
            for (ServiceTripCrews item : crews) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        if (tripNoList != null && !tripNoList.isEmpty()) {
            ServiceTrip userTripEntity = new ServiceTrip();
            userTripEntity.setStatus(TripStatus.OFFTheCar.getValue());
            //修改司机行程下用户行程状态也为出发状态
            updateIn(dbKey, userTripEntity, tripNoList);
            //同时添加用户行程状态记录
            for (String tripNo1 : tripNoList) {
                TripStatusRecord statusRecord = new TripStatusRecord();
                statusRecord.setOrderNo(tripNo1);
                statusRecord.setStatusName(TripStatus.OFFTheCar.getName());
                statusRecord.setStatusValue(TripStatus.OFFTheCar.getValue());
                statusRecord.setTip(TripStatus.OFFTheCar.getTip());
                statusRecord.setTime(SystemUtil.getAllSeconds());
                tripStatusRecordService.insert(dbKey, statusRecord);
            }
        }
        /*if (row > 0) {
            //如为城际通，则需要修改乘客的订单状态
            if (driverTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
                ServiceTrip crewsQuery = new ServiceTrip();
                crewsQuery.setSchedulId(driverTrip.getSchedulId());
                crewsQuery.setDriverOpenId(driverTrip.getDriverOpenId());
                List<ServiceTrip> crews = selectList("", crewsQuery);
                if (crews != null && crews.size() > 0) {
                    //添加乘客行程状态
                    for (ServiceTrip serviceTrip : crews) {

                        ServiceTrip userTripEntity = new ServiceTrip();
                        userTripEntity.setTripNo(serviceTrip.getTripNo());
                        userTripEntity.setStatus(TripStatus.OFFTheCar.getValue());
                        updateByKey(dbKey, userTripEntity);

                        TripStatusRecord statusRecord = new TripStatusRecord();
                        statusRecord.setOrderNo(serviceTrip.getTripNo());
                        statusRecord.setStatusName(TripStatus.OFFTheCar.getName());
                        statusRecord.setStatusValue(TripStatus.OFFTheCar.getValue());
                        statusRecord.setTip(TripStatus.OFFTheCar.getTip());
                        statusRecord.setTime(SystemUtil.getAllSeconds());
                        tripStatusRecordService.insert(dbKey, statusRecord);
                    }
                }
            }
        }*/
        if (row > 0) {
            //推送通知所有乘客--确认用户下车
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String tripNo = userTrip.getTripNo();
                    String toUser = "";
                    String serviceCode = userTrip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    String message = String.format("司机%s行程确认用户下车", moduleName);
                    String content = String.format("司机%s行程确认用户下车,行程号为：%s", moduleName, tripNo);

                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(userTrip.getOpenId());
                    toUser = userTrip.getOpenId();

                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.TripCrewDownCar.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(tripNo);
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                }
            }).start();
        }
        if (row > 0) {
            Driver driver = driverService.getDriverByOpenId("", userTrip.getDriverOpenId());
            if (driver != null) {
                OperateArrive operateArrive = new OperateArrive();
                operateArrive.setCompanyId("5201HDCX8779");
                operateArrive.setOrderId(userTrip.getTripNo());
                operateArrive.setDestLongitude(driver.getLon());
                operateArrive.setDestLatitude(driver.getLat());
                operateArrive.setEncrypt(2L);
                operateArrive.setDestTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
                operateArrive.setDriveMile(userTrip.getDistance() / 1000);
                operateArrive.setDriveTime(userTrip.getDuration());
                operateArrive.setDestTime2(0L);
                operateArriveService.insertUpper("", operateArrive);
            }
        }
        return row > 0;
    }

    /**
     * 司机发起支付
     *
     * @param dbKey
     * @param driverTrip 司机订单
     * @return
     * @throws Exception
     */
    @Override
    public Boolean driverSurePay(final String dbKey, ServiceTrip driverTrip, final ServiceTrip userTrip, List<ServiceTripCrews> crews, Double roadPrice, Double parkPrice) throws Exception {
        if (driverTrip == null)
            return false;
        //修改行程订单的状态为用户上车
        //修改用户订单状态为上车
        final String drivertripNo = driverTrip.getTripNo();
        String usertripNo = userTrip.getTripNo();

        //重新计算费用
        Double price = calcultePrice(dbKey, userTrip);
        if (price <= 0.0) {
            return false;
        }
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(usertripNo);
        tripEntity.setStatus(TripStatus.WaitingPay.getValue());
        //Double price = driverTrip.getPayFee();
        if (roadPrice != null && roadPrice > 0) {
            price = ConvertUtil.toFiexd(price + roadPrice);
        }
        if (parkPrice != null && parkPrice > 0) {
            price = ConvertUtil.toFiexd(price + parkPrice);
        }
        tripEntity.setPayFee(price);
        int row = updateByKey(dbKey, tripEntity);

        ServiceTrip driverEntity = new ServiceTrip();
        driverEntity.setTripNo(drivertripNo);
        driverEntity.setStatus(TripStatus.WaitingPay.getValue());
        driverEntity.setPayFee(price);
        updateByKey(dbKey, driverEntity);
        if (row > 0) {
            //修改司机状态为在线
            String driverOpenId = driverTrip.getDriverOpenId();
            Driver driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
            if (driver != null) {
                Driver driver1 = new Driver();
                driver1.setDriverId(driver.getDriverId());
                driver1.setStatus(DriverStatus.OnLine.getValue());
                driverService.updateByKey(dbKey, driver1);
            }
            if (roadPrice != null && roadPrice > 0) {
                //添加费用记录
                ServicePriceRecord pricerecord = new ServicePriceRecord();
                pricerecord.setPrice(roadPrice);
                pricerecord.setTripNo(usertripNo);
                pricerecord.setName("过路费");
                pricerecord.setDes("支付过路费");
                pricerecord.setPriceType(1);
                pricerecord.setUpdateTime(SystemUtil.getAllSeconds());
                servicePriceRecordService.insert(dbKey, pricerecord);
            }
            if (parkPrice != null && parkPrice > 0) {
                //添加费用记录
                ServicePriceRecord pricerecord = new ServicePriceRecord();
                pricerecord.setPrice(roadPrice);
                pricerecord.setTripNo(usertripNo);
                pricerecord.setName("停车费");
                pricerecord.setPriceType(2);
                pricerecord.setDes("支付停车费");
                pricerecord.setUpdateTime(SystemUtil.getAllSeconds());
                servicePriceRecordService.insert(dbKey, pricerecord);
            }

            //添加订单状态
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(drivertripNo);
            statusRecord.setStatusName(TripStatus.WaitingPay.getName());
            statusRecord.setStatusValue(TripStatus.WaitingPay.getValue());
            statusRecord.setTip(TripStatus.WaitingPay.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            row = tripStatusRecordService.insert(dbKey, statusRecord);
        }
        final List<String> tripNoList = new ArrayList<String>();
        if (crews != null && !crews.isEmpty()) {
            for (ServiceTripCrews item : crews) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        if (tripNoList != null && !tripNoList.isEmpty()) {
            ServiceTrip userTripEntity = new ServiceTrip();
            userTripEntity.setStatus(TripStatus.WaitingPay.getValue());
            //修改司机行程下用户行程状态也为出发状态
            updateIn(dbKey, userTripEntity, tripNoList);
            //同时添加用户行程状态记录
            for (String tripNo1 : tripNoList) {
                TripStatusRecord statusRecord = new TripStatusRecord();
                statusRecord.setOrderNo(tripNo1);
                statusRecord.setStatusName(TripStatus.WaitingPay.getName());
                statusRecord.setStatusValue(TripStatus.WaitingPay.getValue());
                statusRecord.setTip(TripStatus.WaitingPay.getTip());
                statusRecord.setTime(SystemUtil.getAllSeconds());
                tripStatusRecordService.insert(dbKey, statusRecord);
            }
        }
        if (row > 0) {
            //推送通知所有乘客--发起支付
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String tripNo = userTrip.getTripNo();
                    String toUser = "";
                    String serviceCode = userTrip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    String message = String.format("司机%s行程发起支付", moduleName);
                    String content = String.format("司机%s行程发起支付,行程号为：%s", moduleName, tripNo);

                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(userTrip.getOpenId());
                    toUser = userTrip.getOpenId();

                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.TripPay.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(tripNo);
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                }
            }).start();
        }
        return row > 0;
    }


    @Override
    @Transactional
    public synchronized Boolean driverCompleteTrip(final String dbKey, final ServiceTrip trip) throws Exception {
        if (trip == null) return false;
        //获取行程所有乘客订单
        final String tripNo = trip.getTripNo();
        final String serviceCode = trip.getServiceCode();
        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setDriverTripNo(tripNo);
        crewsQuery.setDriverOpenId(trip.getOpenId());

        final List<ServiceTripCrews> crews = serviceTripCrewsService.selectList(dbKey, crewsQuery);
        //用户行程单号列表
        List<String> tripNoList = new ArrayList<String>();
        if (crews != null && !crews.isEmpty()) {
            for (ServiceTripCrews item : crews) {
                tripNoList.add(item.getCrewTripNo());
            }
        }
        logger.error("driverCompleteTrip.tripNoList=" + JSON.toJSONString(tripNoList));
        //修改行程状态
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(trip.getTripNo());
        tripEntity.setStatus(TripStatus.Complete.getValue());
        tripEntity.setCompleteTime(SystemUtil.getAllSeconds());
        int row = updateByKey(dbKey, tripEntity);

        //修改司机状态为在线
        String driverOpenId = trip.getDriverOpenId();
        Driver driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
        //修改司机状态为在线
        if (row > 0) {
            //订单数增加一
            if (driver != null) {
                int orderCount = driver.getOrderCount() == null ? 0 : driver.getOrderCount();
                orderCount += 1;
                Driver driverEntity = new Driver();
                driverEntity.setDriverId(driver.getDriverId());
                driverEntity.setOrderCount(orderCount);
                driverEntity.setStatus(DriverStatus.OnLine.getValue());
                driverService.updateByKey(dbKey, driverEntity);
            }
            //添加司机行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.Complete.getName());
            statusRecord.setStatusValue(TripStatus.Complete.getValue());
            statusRecord.setTip(TripStatus.Complete.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            tripStatusRecordService.insert(dbKey, statusRecord);
        }
        //修改用户行程状态，修改司机行程乘客列表状态
        if (tripNoList != null && !tripNoList.isEmpty()) {
            //修改用户行程状态
            ServiceTrip userTripEntity = new ServiceTrip();
            userTripEntity.setStatus(TripStatus.Complete.getValue());
            userTripEntity.setCompleteTime(SystemUtil.getAllSeconds());
            updateIn(dbKey, userTripEntity, tripNoList);
            //添加用户行程状态记录
            //同时添加用户行程状态记录
            for (String userTripNo : tripNoList) {
                TripStatusRecord statusRecord = new TripStatusRecord();
                statusRecord.setOrderNo(userTripNo);
                statusRecord.setStatusName(TripStatus.Complete.getName());
                statusRecord.setStatusValue(TripStatus.Complete.getValue());
                statusRecord.setTip(TripStatus.Complete.getTip());
                statusRecord.setTime(SystemUtil.getAllSeconds());
                tripStatusRecordService.insert(dbKey, statusRecord);
            }

            //修改司机行程乘客列表状态
            ServiceTripCrews tripCrewsEntity = new ServiceTripCrews();
            tripCrewsEntity.setCrewStatus(TripCrewStatus.Complete.getValue());
            tripCrewsEntity.setCrewOffTime(SystemUtil.getAllSeconds());
            tripCrewsEntity.setDriverTripNo(tripNo);
            serviceTripCrewsService.updateIn(dbKey, tripCrewsEntity, tripNoList);
        }

        //查询业务以及收费比例
        double chargeRatio = 0.0;
        double subChargeRatio = 0.0;
        if (serviceCode.equals(ServiceCode.CJT.getCode())) {
            //城际通业务存在 司机，总公司，分公司，一级票务经理  二级票务经理
            CjtRoad queryroad = new CjtRoad();
            queryroad.setId(trip.getRoadId());
            CjtRoad cjtRoad = cjtRoadService.selectOne(dbKey, queryroad);
            if (cjtRoad != null) {
                chargeRatio = cjtRoad.getChargeRatio();
                subChargeRatio = cjtRoad.getSubChargeRatio();
            }
        } else {
            //其他业务，司机，总公司
            Companyfare queryfare = new Companyfare();
            queryfare.setCompanyId(trip.getCompanyId());
            queryfare.setServiceCode(serviceCode);
            Companyfare companyfare = companyfareService.selectOne(dbKey, queryfare);
            if (companyfare != null) {
                chargeRatio = companyfare.getChargeRatio();
                subChargeRatio = companyfare.getSubChargeRatio();
            }
        }

        //获取所有用户行程,并按照规则转账给司机和平台
        if (tripNoList != null && !tripNoList.isEmpty()) {
            List<ServiceTrip> userTripList = selectListIn(dbKey, null, tripNoList);
            if (crews != null && !crews.isEmpty()) {
                for (ServiceTrip userTrip : userTripList) {
                    //计算公司收费比例,不同的业务是不一样的
                    //如果行程余额部分走了线上支付
                    if (userTrip.getPayStatus() != null && userTrip.getPayFee() != null &&
                            (userTrip.getPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue() ||
                                    userTrip.getPayStatus() == TradePayStatus.TRADE_FINISHED.getValue())) {
                        //公司按收费比例扣除的费用
                        double totalFee = userTrip.getPayFee() == null ? 0 : userTrip.getPayFee();
                        //判断该行程是否存在过路费和停车费
                        double roadPrice = 0.0;
                        double parkPrice = 0.0;
                        if (!serviceCode.equals(ServiceCode.CJT.getCode())) {
                            //除城际通外，其他业务去除
                            ServicePriceRecord pricerecord1 = new ServicePriceRecord();
                            pricerecord1.setTripNo(userTrip.getTripNo());
                            List<ServicePriceRecord> pricelist = servicePriceRecordService.selectList(dbKey, pricerecord1);
                            if (pricelist != null && pricelist.size() > 0) {
                                for (ServicePriceRecord priceRecord : pricelist) {
                                    if (priceRecord.getPriceType() == 1) {
                                        roadPrice = priceRecord.getPrice();
                                    } else if (priceRecord.getPriceType() == 2) {
                                        parkPrice = priceRecord.getPrice();
                                    }
                                }
                            }
                        }
                        if (roadPrice > 0) {
                            totalFee = ConvertUtil.toFiexd(totalFee - roadPrice);
                        }
                        if (parkPrice > 0) {
                            totalFee = ConvertUtil.toFiexd(totalFee - parkPrice);
                        }

                        double deductFee = totalFee * chargeRatio;
                        double deductFee_sub = totalFee * subChargeRatio;

                        //给司机的费用，这个费用存入司机的余额中
                        double giveDriverFee = ConvertUtil.toFiexd(totalFee - deductFee - deductFee_sub + roadPrice + parkPrice);
                        if (giveDriverFee < 0)
                            giveDriverFee = 0;
                        //重新获取司机信息
                        driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
                        double beforeBalance = driver.getBalance() == null ? 0 : driver.getBalance();
                        double afterBalance = beforeBalance + giveDriverFee;
                        //司机总收入
                        double income = driver.getIncome() == null ? 0 : driver.getIncome();
                        income += giveDriverFee;

                        //任务完成后要把钱赚到服务人的余额中。
                        //1、修改司机余额
                        //2、添加司机余额充值记录
                        //3、添加平台流水出账记录(用户支付属于进账记录)
                        //4、如果公司有收费金额，修改公司的余额，添加公司级余额充值记录
                        //5、如果公司有收费金额，添加平台流水进账记录
                        Driver driverEntity = new Driver();
                        driverEntity.setDriverId(driver.getDriverId());
                        driverEntity.setBalance(afterBalance);
                        driverEntity.setIncome(income);
                        driverService.updateByKey(dbKey, driverEntity);
                        //司机余额充值记录
                        RechargeRecord record = new RechargeRecord();
                        record.setRecordNo(SystemUtil.generateRandomNo(""));
                        record.setPhoneNo(driver.getOpenId());
                        record.setUserType(PlatformUserType.DRIVER_USER.getValue());
                        record.setRechargeMoney(giveDriverFee);
                        record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                        record.setBeforeBalance(beforeBalance);
                        record.setAfterBalance(afterBalance);
                        record.setRechargeTime(SystemUtil.getAllSeconds());
                        record.setRechargeType(RechargeType.CompleteTrip.getValue());
                        record.setOperator("system");
                        record.setRemark("司机完成行程后将用户付款金额按比例转入司机余额");
                        record.setLinkTaskNo(userTrip.getTripNo());
                        rechargeRecordService.insert(dbKey, record);

                        //添加平台流水出账记录
                        PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
                        flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                        flowRecord.setUserUniqueId(driver.getOpenId());
                        flowRecord.setUserType(PlatformUserType.DRIVER_USER.getValue());
                        flowRecord.setFlowAmount(giveDriverFee);

                        //ycs 2019-05-25
                        //flowRecord.setInOut(FlowInOut.OUT.getValue());
                        flowRecord.setInOut(FlowInOut.IN.getValue());
                        flowRecord.setFlowFrom("平台" + userTrip.getPayName());
                        flowRecord.setFlowTo("司机余额");
                        int flowMode = userTrip.getPayId() == null ? 0 : userTrip.getPayId();
                        flowRecord.setFlowMode(flowMode);
                        flowRecord.setLinkNo(userTrip.getTripNo());
                        flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                        platformFundFlowRecordService.insert(dbKey, flowRecord);

                        double price1 = 0.0;
                        double price2 = 0.0;
                        //城际通->推荐人奖励
                        if (serviceCode.equals(ServiceCode.CJT.getCode())) {
                            //userTrip.getLinkUser()
                            User user = userService.getUserByOpenId(dbKey, userTrip.getOpenId());
                            if (user != null) {
                                //查询推荐人
                                Map<String, Double> mapPrice = ticketUserService.calcatePrice(dbKey, user.getPhoneNo(), userTrip.getTripNo(), totalFee);
                                if (mapPrice != null) {
                                    price1 = mapPrice.get("price1");
                                    price2 = mapPrice.get("price2");
                                }
                            }
                        }
                        //推荐人奖励从公司收益中扣除
                        deductFee = ConvertUtil.toFiexd(deductFee - price1 - price2);
                        /**
                         * 总公司、分公司余额
                         */
                        //1、总公司
                        PlatformUser puQuery = new PlatformUser();
                        if (deductFee > 0.0 || deductFee < 0.0) {
                            puQuery.setUserId(PLATFORM_USER_ID);
                            puQuery.setEnabled(true);
                            PlatformUser platformUser = platformUserService.selectOne(dbKey, puQuery);
                            if (platformUser == null) {
                                platformUser = new PlatformUser();
                                platformUser.setUserId(PLATFORM_USER_ID);
                                platformUser.setBalance(0.0);
                                platformUser.setEnabled(true);
                                platformUserService.insert(dbKey, platformUser);
                            }
                            double puBeforeBalance = platformUser.getBalance() == null ? 0 : platformUser.getBalance();
                            double puAfterBalance = puBeforeBalance + deductFee;
                            PlatformUser puEntity = new PlatformUser();
                            puEntity.setUserId(PLATFORM_USER_ID);
                            puEntity.setBalance(puAfterBalance);
                            platformUserService.updateByKey(dbKey, puEntity);

                            record = new RechargeRecord();
                            record.setRecordNo(SystemUtil.generateRandomNo(""));
                            record.setPhoneNo(PLATFORM_USER_ID);
                            record.setUserType(PlatformUserType.PLATFORM_USER.getValue());
                            record.setRechargeMoney(deductFee);
                            record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                            record.setBeforeBalance(puBeforeBalance);
                            record.setAfterBalance(puAfterBalance);
                            record.setRechargeTime(SystemUtil.getAllSeconds());
                            record.setRechargeType(RechargeType.CompleteTrip.getValue());
                            record.setOperator("system");
                            record.setRemark("司机完成行程后按公司收费比例转入公司余额");
                            record.setLinkTaskNo(tripNo);
                            rechargeRecordService.insert(dbKey, record);

                            //添加平台流水进账记录
                            flowRecord = new PlatformFundFlowRecord();
                            flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                            flowRecord.setUserUniqueId(PLATFORM_USER_ID);
                            flowRecord.setUserType(PlatformUserType.PLATFORM_USER.getValue());
                            flowRecord.setFlowAmount(deductFee);
                            flowRecord.setInOut(FlowInOut.IN.getValue());
                            flowRecord.setFlowFrom("平台" + userTrip.getPayName());
                            flowRecord.setFlowTo("公司余额");
                            flowRecord.setFlowMode(flowMode);
                            flowRecord.setLinkNo(userTrip.getTripNo());
                            flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                            platformFundFlowRecordService.insert(dbKey, flowRecord);

                        }

                        //2、分公司
                        if (deductFee_sub > 0) {
                            puQuery = new PlatformUser();
                            puQuery.setUserId(userTrip.getCompanyId() + "");
                            puQuery.setEnabled(true);
                            PlatformUser platformUser = platformUserService.selectOne(dbKey, puQuery);
                            if (platformUser == null) {
                                platformUser = new PlatformUser();
                                platformUser.setUserId(userTrip.getCompanyId() + "");
                                platformUser.setBalance(0.0);
                                platformUser.setEnabled(true);
                                platformUserService.insert(dbKey, platformUser);
                            }
                            double puBeforeBalance = platformUser.getBalance() == null ? 0 : platformUser.getBalance();
                            double puAfterBalance = puBeforeBalance + deductFee_sub;
                            PlatformUser puEntity = new PlatformUser();
                            puEntity.setUserId(userTrip.getCompanyId() + "");
                            puEntity.setBalance(puAfterBalance);
                            platformUserService.updateByKey(dbKey, puEntity);

                            record = new RechargeRecord();
                            record.setRecordNo(SystemUtil.generateRandomNo(""));
                            record.setPhoneNo(userTrip.getCompanyId() + "");
                            record.setUserType(PlatformUserType.SUB_PLATFORM_USER.getValue());
                            record.setRechargeMoney(deductFee_sub);
                            record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                            record.setBeforeBalance(puBeforeBalance);
                            record.setAfterBalance(puAfterBalance);
                            record.setRechargeTime(SystemUtil.getAllSeconds());
                            record.setRechargeType(RechargeType.CompleteTrip.getValue());
                            record.setOperator("system");
                            record.setRemark("司机完成行程后按分公司收费比例转入分公司余额");
                            record.setLinkTaskNo(tripNo);
                            rechargeRecordService.insert(dbKey, record);

                            //添加平台流水进账记录
                            flowRecord = new PlatformFundFlowRecord();
                            flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                            flowRecord.setUserUniqueId(userTrip.getCompanyId() + "");
                            flowRecord.setUserType(PlatformUserType.SUB_PLATFORM_USER.getValue());
                            flowRecord.setFlowAmount(deductFee_sub);
                            flowRecord.setInOut(FlowInOut.IN.getValue());
                            flowRecord.setFlowFrom("平台" + userTrip.getPayName());
                            flowRecord.setFlowTo("分公司余额");
                            flowRecord.setFlowMode(flowMode);
                            flowRecord.setLinkNo(userTrip.getTripNo());
                            flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                            platformFundFlowRecordService.insert(dbKey, flowRecord);
                        }
                    }
                }
            }
        }
        if (row > 0) {
            //推送通知所有乘客司机行程已发车
            final List<ServiceTripCrews> finalCrews = crews;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //单个推送给用户
                    for (ServiceTripCrews item : finalCrews) {
                        String tripNo = item.getCrewTripNo();
                        String toUser = "";
                        String serviceCode = trip.getServiceCode();
                        String moduleName = CustomMsgModule.getModuleName(serviceCode);
                        String message = String.format("司机%s行程已结束", moduleName);
                        String content = String.format("司机%s行程已结束,行程号为：%s", moduleName, tripNo);

                        List<String> aliasList = new ArrayList<String>();
                        aliasList.add(item.getCrewTripNo());
                        toUser = item.getCrewTripNo();

                        PushCustomMsg customMsg = new PushCustomMsg();
                        customMsg.setModule(serviceCode);
                        customMsg.setType(CustomMsgType.TripComplete.getValue());
                        customMsg.setKey(tripNo);

                        PushMessage pushMessage = new PushMessage();
                        pushMessage.setContent(content);
                        pushMessage.setModule(serviceCode);
                        pushMessage.setTitle(message);
                        pushMessage.setTripNo(tripNo);
                        pushMessage.setToUser(toUser);
                        pushMessage.setMessage(message);
                        pushMessage.setContent(content);
                        pushMessage.setExtras(customMsg.toJson());
                        pushMessage.setPushTime(SystemUtil.getAllSeconds());
                        pushMessage.setJumpUrl("");

                        pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);

                    }
                }
            }).start();
        }

        return row > 0;
    }


    @Override
    public Boolean paySuccessCompleteTrip(final String dbKey, final ServiceTrip userTrip) throws Exception {
        if (userTrip == null) return false;
        //获取行程所有乘客订单
        final String tripNo = userTrip.getTripNo();

        //修改用户行程状态
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(tripNo);
        tripEntity.setStatus(TripStatus.Complete.getValue());
        tripEntity.setCompleteTime(SystemUtil.getAllSeconds());
        int row = updateByKey(dbKey, tripEntity);

        //修改司机状态为在线
        String driverOpenId = userTrip.getDriverOpenId();
        Driver driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
        //修改司机状态为在线
        if (row > 0) {
            //订单数增加一
            if (driver != null) {
                int orderCount = driver.getOrderCount() == null ? 0 : driver.getOrderCount();
                orderCount += 1;
                Driver driverEntity = new Driver();
                driverEntity.setDriverId(driver.getDriverId());
                driverEntity.setOrderCount(orderCount);
                driverEntity.setStatus(DriverStatus.OnLine.getValue());
                driverService.updateByKey(dbKey, driverEntity);
            }
            //添加用户行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.Complete.getName());
            statusRecord.setStatusValue(TripStatus.Complete.getValue());
            statusRecord.setTip(TripStatus.Complete.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            tripStatusRecordService.insert(dbKey, statusRecord);

            //修改用户
            //修改司机行程乘客列表状态
            ServiceTripCrews tripCrewsEntity = new ServiceTripCrews();
            tripCrewsEntity.setCrewStatus(TripCrewStatus.Complete.getValue());
            tripCrewsEntity.setCrewOffTime(SystemUtil.getAllSeconds());
            tripCrewsEntity.setCrewTripNo(tripNo);
            serviceTripCrewsService.update(dbKey, tripCrewsEntity);
        }

        ServiceTripCrews crewsQuery = new ServiceTripCrews();
        crewsQuery.setCrewTripNo(tripNo);
        crewsQuery.setDriverOpenId(userTrip.getDriverOpenId());
        final ServiceTripCrews driverTrip = serviceTripCrewsService.selectOne(dbKey, crewsQuery);
        if (driverTrip != null) {
            //修改司机行程状态
            ServiceTrip drivertripEntity = new ServiceTrip();
            drivertripEntity.setTripNo(driverTrip.getDriverTripNo());
            drivertripEntity.setStatus(TripStatus.Complete.getValue());
            drivertripEntity.setCompleteTime(SystemUtil.getAllSeconds());
            updateByKey(dbKey, drivertripEntity);

            //添加司机行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(driverTrip.getDriverTripNo());
            statusRecord.setStatusName(TripStatus.Complete.getName());
            statusRecord.setStatusValue(TripStatus.Complete.getValue());
            statusRecord.setTip(TripStatus.Complete.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            tripStatusRecordService.insert(dbKey, statusRecord);

            //修改司机行程状态
            ServiceTripCrews tripCrewsEntity = new ServiceTripCrews();
            tripCrewsEntity.setCrewStatus(TripCrewStatus.Complete.getValue());
            tripCrewsEntity.setCrewOffTime(SystemUtil.getAllSeconds());
            tripCrewsEntity.setDriverTripNo(driverTrip.getDriverTripNo());
            serviceTripCrewsService.update(dbKey, tripCrewsEntity);
        }
        if (row > 0) {
            sepAccount(dbKey, userTrip);
        }

        if (row > 0 && driverTrip != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //单个推送给用户
                    String tripNo = driverTrip.getCrewTripNo();
                    String toUser = "";
                    String serviceCode = userTrip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    String message = String.format("用户已支付，行程已结束");
                    String content = String.format("用户已支付,行程结束,行程号为：%s", tripNo);

                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(driverTrip.getDriverTripNo());
                    toUser = driverTrip.getDriverOpenId();

                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.TripComplete.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(tripNo);
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");
                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Driver, customMsg, aliasList, true);
                }
            }).start();
        }

        return row > 0;
    }

    private void sepAccount(String dbKey, ServiceTrip userTrip) {
        final String serviceCode = userTrip.getServiceCode();
        String tripNo = userTrip.getTripNo();
        double chargeRatio = 0.0;
        double subChargeRatio = 0.0;
        //计算公司收费比例,不同的业务是不一样的
        //专线拼车
        if (ServiceCode.ZXPC.getCode().equals(serviceCode)) {
            //专线拼车是按路线来的
            RoadLine lineQuery = new RoadLine();
            lineQuery.setRoadId(userTrip.getRoadId());
            RoadLine roadLine = roadLineService.selectOne(dbKey, lineQuery);
            if (roadLine != null) {
                chargeRatio = roadLine.getChargeRatio();
                subChargeRatio = roadLine.getSubChargeRatio();
            }
        }//包车业务
        else if (ServiceCode.BC.getCode().equals(serviceCode) ||
                ServiceCode.KC.getCode().equals(serviceCode) ||
                ServiceCode.SFC.getCode().equals(serviceCode)) {
            ServiceConfig configQuery = new ServiceConfig();
            configQuery.setServiceCode(serviceCode);
            configQuery.setEnabled(true);
            ServiceConfig config = serviceConfigService.selectOne(dbKey, configQuery);

            //地区业务配置
            ServiceConfigArea queryArea = new ServiceConfigArea();
            // queryArea.setServiceId(Long.parseLong(config.getCompanyId() + ""));
            //queryArea.setAreaId(userTrip.getAreaCode()+);
            ServiceConfigArea configArea = serviceConfigAreaService.selectOne("", queryArea);

            if (configArea != null && !StringUtils.isBlank(configArea.getOtherConfig())) {
                String otherConfig = configArea.getOtherConfig();

                if (ServiceCode.BC.getCode().equals(serviceCode)) {
                    BCServiceOtherConfig bcConfig = JSON.parseObject(otherConfig, BCServiceOtherConfig.class);
                    chargeRatio = bcConfig == null ? 0 : bcConfig.getChargeRatio();
                    subChargeRatio = bcConfig == null ? 0 : bcConfig.getSubChargeRatio();
                } else if (ServiceCode.KC.getCode().equals(serviceCode)) {
                    KCServiceOtherConfig kcConfig = JSON.parseObject(otherConfig, KCServiceOtherConfig.class);
                    chargeRatio = kcConfig == null ? 0 : kcConfig.getChargeRatio();
                    subChargeRatio = kcConfig == null ? 0 : kcConfig.getSubChargeRatio();
                } else if (ServiceCode.SFC.getCode().equals(serviceCode)) {
                    SFCServiceOtherConfig sfcConfig = JSON.parseObject(otherConfig, SFCServiceOtherConfig.class);
                    chargeRatio = sfcConfig == null ? 0 : sfcConfig.getChargeRatio();
                    subChargeRatio = sfcConfig == null ? 0 : sfcConfig.getSubChargeRatio();
                }
            }
        }
        //如果定金部分走了线上支付
        if (userTrip.getDepositPayStatus() != null && userTrip.getDepositPayFee() != null &&
                (userTrip.getDepositPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue() ||
                        userTrip.getDepositPayStatus() == TradePayStatus.TRADE_FINISHED.getValue())) {
            /**
             *  ycs 2019-05-25
             * */
            //公司、分公司按收费比例扣除的费用
            double totalFee = userTrip.getDepositPayFee() == null ? 0 : userTrip.getDepositPayFee();
            double deductFee = totalFee * chargeRatio / 100;
            double deductFee_sub = totalFee * subChargeRatio / 100;

            //给司机的费用，这个费用存入司机的余额中
            double giveDriverFee = totalFee - deductFee - deductFee_sub;

            if (giveDriverFee < 0)
                giveDriverFee = 0;
            //重新获取司机信息
            String driverOpenId = userTrip.getDriverOpenId();
            Driver driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
            double beforeBalance = driver.getBalance() == null ? 0 : driver.getBalance();
            double afterBalance = beforeBalance + giveDriverFee;
            //司机总收入
            double income = driver.getIncome() == null ? 0 : driver.getIncome();
            income += giveDriverFee;
            //任务完成后要把钱赚到服务人的余额中。
            //1、修改司机余额
            //2、添加司机余额充值记录
            //3、添加平台流水出账记录(用户支付属于进账记录)
            //4、如果公司有收费金额，修改公司的余额，添加公司级余额充值记录
            //5、如果公司有收费金额，添加平台流水进账记录
            Driver driverEntity = new Driver();
            driverEntity.setDriverId(driver.getDriverId());
            driverEntity.setBalance(afterBalance);
            driverEntity.setIncome(income);
            driverService.updateByKey(dbKey, driverEntity);
            //司机余额充值记录
            RechargeRecord record = new RechargeRecord();
            record.setRecordNo(SystemUtil.generateRandomNo(""));
            record.setPhoneNo(driver.getOpenId());
            record.setUserType(PlatformUserType.DRIVER_USER.getValue());
            record.setRechargeMoney(giveDriverFee);
            record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
            record.setBeforeBalance(beforeBalance);
            record.setAfterBalance(afterBalance);
            record.setRechargeTime(SystemUtil.getAllSeconds());
            record.setRechargeType(RechargeType.CompleteTrip.getValue());
            record.setOperator("system");
            record.setRemark("司机完成行程后将用户支付定金按比例转入司机余额");
            record.setLinkTaskNo(userTrip.getTripNo());
            rechargeRecordService.insert(dbKey, record);

            //添加平台流水出账记录  平台 ==> 司机
            PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
            flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
            flowRecord.setUserUniqueId(driver.getOpenId());
            flowRecord.setUserType(PlatformUserType.DRIVER_USER.getValue());
            flowRecord.setFlowAmount(giveDriverFee);

            //ycs 2019-05-25
            //flowRecord.setInOut(FlowInOut.OUT.getValue());
            flowRecord.setInOut(FlowInOut.IN.getValue());

            flowRecord.setFlowFrom("平台" + userTrip.getDepositPayName());
            flowRecord.setFlowTo("司机余额");
            int flowMode = userTrip.getDepositPayId() == null ? 0 : userTrip.getDepositPayId();
            flowRecord.setFlowMode(flowMode);
            flowRecord.setLinkNo(userTrip.getTripNo());
            flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
            platformFundFlowRecordService.insert(dbKey, flowRecord);

            if (deductFee > 0) {
                /**
                 * 公司、分公司余额
                 */
                //1、公司
                PlatformUser puQuery = new PlatformUser();
                puQuery.setUserId(PLATFORM_USER_ID);
                puQuery.setEnabled(true);
                PlatformUser platformUser = platformUserService.selectOne(dbKey, puQuery);
                if (platformUser == null) {
                    platformUser = new PlatformUser();
                    platformUser.setUserId(PLATFORM_USER_ID);
                    platformUser.setBalance(0.0);
                    platformUser.setEnabled(true);
                    platformUserService.insert(dbKey, platformUser);
                }
                double puBeforeBalance = platformUser.getBalance() == null ? 0 : platformUser.getBalance();
                double puAfterBalance = puBeforeBalance + deductFee;
                PlatformUser puEntity = new PlatformUser();
                puEntity.setUserId(PLATFORM_USER_ID);
                puEntity.setBalance(puAfterBalance);
                platformUserService.updateByKey(dbKey, puEntity);

                record = new RechargeRecord();
                record.setRecordNo(SystemUtil.generateRandomNo(""));
                record.setPhoneNo(PLATFORM_USER_ID);
                record.setUserType(PlatformUserType.PLATFORM_USER.getValue());
                record.setRechargeMoney(deductFee);
                record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                record.setBeforeBalance(puBeforeBalance);
                record.setAfterBalance(puAfterBalance);
                record.setRechargeTime(SystemUtil.getAllSeconds());
                record.setRechargeType(RechargeType.CompleteTrip.getValue());
                record.setOperator("system");

                //record.setRemark("司机完成行程后按公司收费比例将定金转入平台用户余额充值");
                record.setRemark("司机完成行程后按公司收费比例转入公司余额");

                record.setLinkTaskNo(tripNo);
                rechargeRecordService.insert(dbKey, record);

                //添加平台流水进账记录
                flowRecord = new PlatformFundFlowRecord();
                flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                flowRecord.setUserUniqueId(PLATFORM_USER_ID);
                flowRecord.setUserType(PlatformUserType.PLATFORM_USER.getValue());
                flowRecord.setFlowAmount(deductFee);
                flowRecord.setInOut(FlowInOut.IN.getValue());

                //flowRecord.setFlowFrom("平台"+userTrip.getDepositPayName());
                //flowRecord.setFlowTo("平台余额");
                flowRecord.setFlowFrom("平台" + userTrip.getDepositPayName());
                flowRecord.setFlowTo("公司余额");

                flowRecord.setFlowMode(flowMode);
                flowRecord.setLinkNo(userTrip.getTripNo());
                flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                platformFundFlowRecordService.insert(dbKey, flowRecord);

                //2、分公司
                puQuery = new PlatformUser();
                puQuery.setUserId(userTrip.getCompanyId() + "");
                puQuery.setEnabled(true);
                platformUser = platformUserService.selectOne(dbKey, puQuery);
                if (platformUser == null) {
                    platformUser = new PlatformUser();
                    platformUser.setUserId(userTrip.getCompanyId() + "");
                    platformUser.setBalance(0.0);
                    platformUser.setEnabled(true);
                    platformUserService.insert(dbKey, platformUser);
                }
                puBeforeBalance = platformUser.getBalance() == null ? 0 : platformUser.getBalance();
                puAfterBalance = puBeforeBalance + deductFee_sub;
                puEntity = new PlatformUser();
                puEntity.setUserId(userTrip.getCompanyId() + "");
                puEntity.setBalance(puAfterBalance);
                platformUserService.updateByKey(dbKey, puEntity);

                record = new RechargeRecord();
                record.setRecordNo(SystemUtil.generateRandomNo(""));
                record.setPhoneNo(userTrip.getCompanyId() + "");
                record.setUserType(PlatformUserType.SUB_PLATFORM_USER.getValue());
                record.setRechargeMoney(deductFee_sub);
                record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                record.setBeforeBalance(puBeforeBalance);
                record.setAfterBalance(puAfterBalance);
                record.setRechargeTime(SystemUtil.getAllSeconds());
                record.setRechargeType(RechargeType.CompleteTrip.getValue());
                record.setOperator("system");

                //record.setRemark("司机完成行程后按分公司收费比例将定金转入平台用户余额充值");
                record.setRemark("司机完成行程后按分公司收费比例转入分公司余额");

                record.setLinkTaskNo(tripNo);
                rechargeRecordService.insert(dbKey, record);

                //添加平台流水进账记录
                flowRecord = new PlatformFundFlowRecord();
                flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                flowRecord.setUserUniqueId(userTrip.getCompanyId() + "");
                flowRecord.setUserType(PlatformUserType.SUB_PLATFORM_USER.getValue());
                flowRecord.setFlowAmount(deductFee_sub);
                flowRecord.setInOut(FlowInOut.IN.getValue());

                //flowRecord.setFlowFrom("平台"+userTrip.getDepositPayName());
                //flowRecord.setFlowTo("平台余额");
                flowRecord.setFlowFrom("平台" + userTrip.getDepositPayName());
                flowRecord.setFlowTo("分公司余额");

                flowRecord.setFlowMode(flowMode);
                flowRecord.setLinkNo(userTrip.getTripNo());
                flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                platformFundFlowRecordService.insert(dbKey, flowRecord);
            }
        }
        //如果行程余额部分走了线上支付
        if (userTrip.getPayStatus() != null && userTrip.getPayFee() != null &&
                (userTrip.getPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue() ||
                        userTrip.getPayStatus() == TradePayStatus.TRADE_FINISHED.getValue())) {
            //公司按收费比例扣除的费用
            double totalFee = userTrip.getPayFee() == null ? 0 : userTrip.getPayFee();
            double deductFee = totalFee * chargeRatio / 100;
            double deductFee_sub = totalFee * subChargeRatio / 100;

            //给司机的费用，这个费用存入司机的余额中
            double giveDriverFee = totalFee - deductFee - deductFee_sub;
            if (giveDriverFee < 0)
                giveDriverFee = 0;
            //重新获取司机信息
            String driverOpenId = userTrip.getDriverOpenId();
            Driver driver = driverService.getDriverByOpenId(dbKey, driverOpenId);
            double beforeBalance = driver.getBalance() == null ? 0 : driver.getBalance();
            double afterBalance = beforeBalance + giveDriverFee;
            //司机总收入
            double income = driver.getIncome() == null ? 0 : driver.getIncome();
            income += giveDriverFee;
            //任务完成后要把钱赚到服务人的余额中。
            //1、修改司机余额
            //2、添加司机余额充值记录
            //3、添加平台流水出账记录(用户支付属于进账记录)
            //4、如果公司有收费金额，修改公司的余额，添加公司级余额充值记录
            //5、如果公司有收费金额，添加平台流水进账记录
            Driver driverEntity = new Driver();
            driverEntity.setDriverId(driver.getDriverId());
            driverEntity.setBalance(afterBalance);
            driverEntity.setIncome(income);
            driverService.updateByKey(dbKey, driverEntity);
            //司机余额充值记录
            RechargeRecord record = new RechargeRecord();
            record.setRecordNo(SystemUtil.generateRandomNo(""));
            record.setPhoneNo(driver.getOpenId());
            record.setUserType(PlatformUserType.DRIVER_USER.getValue());
            record.setRechargeMoney(giveDriverFee);
            record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
            record.setBeforeBalance(beforeBalance);
            record.setAfterBalance(afterBalance);
            record.setRechargeTime(SystemUtil.getAllSeconds());
            record.setRechargeType(RechargeType.CompleteTrip.getValue());
            record.setOperator("system");
            record.setRemark("司机完成行程后将用户付款金额按比例转入司机余额");
            record.setLinkTaskNo(userTrip.getTripNo());
            rechargeRecordService.insert(dbKey, record);

            //添加平台流水出账记录
            PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
            flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
            flowRecord.setUserUniqueId(driver.getOpenId());
            flowRecord.setUserType(PlatformUserType.DRIVER_USER.getValue());
            flowRecord.setFlowAmount(giveDriverFee);

            //ycs 2019-05-25
            //flowRecord.setInOut(FlowInOut.OUT.getValue());
            flowRecord.setInOut(FlowInOut.IN.getValue());

            flowRecord.setFlowFrom("平台" + userTrip.getPayName());
            flowRecord.setFlowTo("司机余额");
            int flowMode = userTrip.getPayId() == null ? 0 : userTrip.getPayId();
            flowRecord.setFlowMode(flowMode);
            flowRecord.setLinkNo(userTrip.getTripNo());
            flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
            platformFundFlowRecordService.insert(dbKey, flowRecord);

            if (deductFee > 0) {
                /**
                 * 总公司、分公司余额
                 */
                //1、总公司
                PlatformUser puQuery = new PlatformUser();
                puQuery.setUserId(PLATFORM_USER_ID);
                puQuery.setEnabled(true);
                PlatformUser platformUser = platformUserService.selectOne(dbKey, puQuery);
                if (platformUser == null) {
                    platformUser = new PlatformUser();
                    platformUser.setUserId(PLATFORM_USER_ID);
                    platformUser.setBalance(0.0);
                    platformUser.setEnabled(true);
                    platformUserService.insert(dbKey, platformUser);
                }
                double puBeforeBalance = platformUser.getBalance() == null ? 0 : platformUser.getBalance();
                double puAfterBalance = puBeforeBalance + deductFee;
                PlatformUser puEntity = new PlatformUser();
                puEntity.setUserId(PLATFORM_USER_ID);
                puEntity.setBalance(puAfterBalance);
                platformUserService.updateByKey(dbKey, puEntity);

                record = new RechargeRecord();
                record.setRecordNo(SystemUtil.generateRandomNo(""));
                record.setPhoneNo(PLATFORM_USER_ID);
                record.setUserType(PlatformUserType.PLATFORM_USER.getValue());
                record.setRechargeMoney(deductFee);
                record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                record.setBeforeBalance(puBeforeBalance);
                record.setAfterBalance(puAfterBalance);
                record.setRechargeTime(SystemUtil.getAllSeconds());
                record.setRechargeType(RechargeType.CompleteTrip.getValue());
                record.setOperator("system");
                record.setRemark("司机完成行程后按公司收费比例转入公司余额");
                record.setLinkTaskNo(tripNo);
                rechargeRecordService.insert(dbKey, record);

                //添加平台流水进账记录
                flowRecord = new PlatformFundFlowRecord();
                flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                flowRecord.setUserUniqueId(PLATFORM_USER_ID);
                flowRecord.setUserType(PlatformUserType.PLATFORM_USER.getValue());
                flowRecord.setFlowAmount(deductFee);
                flowRecord.setInOut(FlowInOut.IN.getValue());
                flowRecord.setFlowFrom("平台" + userTrip.getPayName());
                flowRecord.setFlowTo("公司余额");
                flowRecord.setFlowMode(flowMode);
                flowRecord.setLinkNo(userTrip.getTripNo());
                flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                platformFundFlowRecordService.insert(dbKey, flowRecord);

                //2、分公司
                puQuery = new PlatformUser();
                puQuery.setUserId(userTrip.getCompanyId() + "");
                puQuery.setEnabled(true);
                platformUser = platformUserService.selectOne(dbKey, puQuery);
                if (platformUser == null) {
                    platformUser = new PlatformUser();
                    platformUser.setUserId(userTrip.getCompanyId() + "");
                    platformUser.setBalance(0.0);
                    platformUser.setEnabled(true);
                    platformUserService.insert(dbKey, platformUser);
                }
                puBeforeBalance = platformUser.getBalance() == null ? 0 : platformUser.getBalance();
                puAfterBalance = puBeforeBalance + deductFee_sub;
                puEntity = new PlatformUser();
                puEntity.setUserId(userTrip.getCompanyId() + "");
                puEntity.setBalance(puAfterBalance);
                platformUserService.updateByKey(dbKey, puEntity);

                record = new RechargeRecord();
                record.setRecordNo(SystemUtil.generateRandomNo(""));
                record.setPhoneNo(userTrip.getCompanyId() + "");
                record.setUserType(PlatformUserType.SUB_PLATFORM_USER.getValue());
                record.setRechargeMoney(deductFee_sub);
                record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                record.setBeforeBalance(puBeforeBalance);
                record.setAfterBalance(puAfterBalance);
                record.setRechargeTime(SystemUtil.getAllSeconds());
                record.setRechargeType(RechargeType.CompleteTrip.getValue());
                record.setOperator("system");
                record.setRemark("司机完成行程后按分公司收费比例转入分公司余额");
                record.setLinkTaskNo(tripNo);
                rechargeRecordService.insert(dbKey, record);

                //添加平台流水进账记录
                flowRecord = new PlatformFundFlowRecord();
                flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                flowRecord.setUserUniqueId(userTrip.getCompanyId() + "");
                flowRecord.setUserType(PlatformUserType.SUB_PLATFORM_USER.getValue());
                flowRecord.setFlowAmount(deductFee_sub);
                flowRecord.setInOut(FlowInOut.IN.getValue());
                flowRecord.setFlowFrom("平台" + userTrip.getPayName());
                flowRecord.setFlowTo("分公司余额");
                flowRecord.setFlowMode(flowMode);
                flowRecord.setLinkNo(userTrip.getTripNo());
                flowRecord.setPurpose(FlowPurpose.DRIVER_COMPLETE_TRIP.getName());
                platformFundFlowRecordService.insert(dbKey, flowRecord);
            }
        }

    }

    @Override
    @Transactional
    public Boolean userComment(String dbKey, ServiceTrip trip, int star, String content) throws Exception {
        if (trip == null || StringUtils.isBlank(trip.getTripNo()))
            return false;
        if (trip.getStatus() != TripStatus.Complete.getValue()) {
            return false;
        }
        if (trip.getHasComment()) {
            return false;
        }
        final String tripNo = trip.getTripNo();
        final String openId = trip.getOpenId();
        ServiceTrip entity = new ServiceTrip();
        entity.setTripNo(tripNo);
        entity.setHasComment(true);

        int row = updateByKey(dbKey, entity);
        if (row > 0) {
            String driverOpenId = trip.getDriverOpenId();
            if (!StringUtils.isBlank(driverOpenId)) {
                Comment comment = new Comment();
                comment.setCommentNo(SystemUtil.generateOrderNo(""));
                comment.setFromOpenId(openId);
                comment.setToOrderNo(tripNo);
                comment.setToOpenId(driverOpenId);
                star = Math.min(5, star);
                star = Math.max(0, star);
                comment.setStar(star);
                comment.setContent(content);
                comment.setTime(SystemUtil.getAllSeconds());
                comment.setEnabled(true);

                row = commentService.insert(dbKey, comment);
                //修改司机的星级
                double driverStar = commentService.calculateStar(dbKey, driverOpenId);
                Driver driverQuery = new Driver();
                driverQuery.setOpenId(driverOpenId);

                Driver driver = driverService.selectOne(dbKey, driverQuery);
                if (driver != null) {
                    Driver driverEntity = new Driver();
                    driverEntity.setDriverId(driver.getDriverId());
                    driverEntity.setStar(driverStar);
                    driverService.updateByKey(dbKey, driverEntity);
                }
            }
        }
        if (row > 0) {
            RatedPassenger ratedPassenger = new RatedPassenger();
            ratedPassenger.setCompanyId("5201HDCX8779");
            ratedPassenger.setOrderId(trip.getTripNo());
            ratedPassenger.setEvaluateTime(Long.parseLong(DateUtil.DatetoString(new Date(), "yyyyMMddHHmmss")));
            ratedPassenger.setServiceScore(star * 1L);
            ratedPassenger.setDetail("content");
            ratedPassenger.setEvaluateTime2(0L);
            ratedPassengerService.insertUpper("", ratedPassenger);
        }
        return row > 0;
    }

    @Override
    @Transactional
    public Boolean driverComment(String dbKey, ServiceTrip trip, String userOpenId, int star, String content) throws Exception {
        if (trip == null || StringUtils.isBlank(trip.getTripNo()))
            return false;
        if (trip.getStatus() != TripStatus.Complete.getValue()) {
            return false;
        }
        /*if(trip.getHasComment()){
            return false;
		}*/
        final String tripNo = trip.getTripNo();
        final String openId = trip.getOpenId();
        //ServiceTrip entity = new ServiceTrip();
        //entity.setTripNo(tripNo);
        //entity.setHasComment(true);

        //int row = updateByKey(dbKey, entity);
        int row = 1;
        if (row > 0) {
            CommentTouser comment = new CommentTouser();
            comment.setCommentNo(SystemUtil.generateOrderNo(""));
            comment.setFromOpenId(openId);
            comment.setToOrderNo(tripNo);
            comment.setToOpenId(userOpenId);
            star = Math.min(5, star);
            star = Math.max(0, star);
            comment.setStar(star);
            comment.setContent(content);
            comment.setTime(SystemUtil.getAllSeconds());
            comment.setEnabled(true);
            row = commentTouserService.insert(dbKey, comment);
            //修改司机的星级
            /*double driverStar = commentService.calculateStar(dbKey, driverOpenId);
            Driver driverQuery = new Driver();
			driverQuery.setOpenId(driverOpenId);

			Driver driver = driverService.selectOne(dbKey, driverQuery);
			if(driver != null){
				Driver driverEntity = new Driver();
				driverEntity.setDriverId(driver.getDriverId());
				driverEntity.setStar(driverStar);
				driverService.updateByKey(dbKey, driverEntity);
			}*/
        }
        return row > 0;
    }

    @Override
    @Transactional
    public Boolean tripExpired(final String dbKey, final ServiceTrip trip) throws Exception {
        if (trip == null)
            return false;
        // 修改行程状态
        final String tripNo = trip.getTripNo();
        ServiceTrip tripEntity = new ServiceTrip();
        tripEntity.setTripNo(tripNo);
        tripEntity.setStatus(TripStatus.Expired.getValue());
        tripEntity.setCompleteTime(SystemUtil.getAllSeconds());
        int row = updateByKey(dbKey, tripEntity);

        if (row > 0) {
            // 添加用户行程状态记录
            TripStatusRecord statusRecord = new TripStatusRecord();
            statusRecord.setOrderNo(tripNo);
            statusRecord.setStatusName(TripStatus.Expired.getName());
            statusRecord.setStatusValue(TripStatus.Expired.getValue());
            statusRecord.setTip(TripStatus.Expired.getTip());
            statusRecord.setTime(SystemUtil.getAllSeconds());
            tripStatusRecordService.insert(dbKey, statusRecord);
            //清除已方式司机可以接单列表中的数据
            ServiceTripCrews tripCrews = new ServiceTripCrews();
            if (trip.getUserType() == PlatformUserType.CLIENT_USER.getValue()) {
                tripCrews.setCrewTripNo(tripNo);
                tripCrews.setCrewOpenId(trip.getOpenId());

                serviceTripCrewsService.delete(dbKey, tripCrews);
            } else if (trip.getUserType() == PlatformUserType.DRIVER_USER.getValue()) {
                tripCrews.setDriverTripNo(tripNo);
                tripCrews.setDriverOpenId(trip.getOpenId());
                serviceTripCrewsService.delete(dbKey, tripCrews);
            }
        }
        // 如果是定金状态，执行定金退换
        // 行程必须是用户的行程且定金已经支付成功
        /*if (trip.getUserType() == PlatformUserType.CLIENT_USER.getValue()
                && trip.getDepositPayFee() != null
                && trip.getDepositPayStatus() != null
                && trip.getDepositPayStatus() == TradePayStatus.TRADE_SUCCESS.getValue()) {

            Boolean refundSucceed = false;
            int refundStatus = TripRefundStatus.FAILED.getValue();
            String openId = trip.getOpenId();
            User user = userService.getUserByOpenId(dbKey, openId);
            // 余额支付
            if (trip.getDepositPayId() == PayType.Balance.getId()) {
                if (user != null) {
                    double depositPayFee = trip.getDepositPayFee() == null ? 0
                            : trip.getDepositPayFee();
                    double beforeBalance = user.getBalance();
                    double afterBalance = user.getBalance() + depositPayFee;
                    User userEntity = new User();
                    userEntity.setUserId(user.getUserId());
                    userEntity.setBalance(afterBalance);
                    int row1 = userService.updateByKey(dbKey, userEntity);
                    refundSucceed = row1 > 0;
                    //退款成功才添加充值记录
                    if (refundSucceed) {
                        // 添加用户充值记录
                        RechargeRecord record = new RechargeRecord();
                        record.setRecordNo(SystemUtil.generateRandomNo(""));
                        record.setPhoneNo(user.getOpenId());
                        record.setUserType(PlatformUserType.CLIENT_USER.getValue());
                        record.setRechargeMoney(depositPayFee);
                        record.setRechargeFrom(RechargeFrom.FROM_SYSTEM.getValue());
                        record.setBeforeBalance(beforeBalance);
                        record.setAfterBalance(afterBalance);
                        record.setRechargeTime(SystemUtil.getAllSeconds());
                        record.setRechargeType(RechargeType.ExpiredTrip.getValue());
                        record.setOperator("system");
                        record.setRemark("用户行程过期退款，余额退款充值");
                        record.setLinkTaskNo(tripNo);
                        rechargeRecordService.insert(dbKey, record);
                    }
                }
            }// 微信支付
            else if (trip.getDepositPayId() == PayType.Tenpay.getId()) {
                // 获取腾讯支付记录
                String payTradeNo = trip.getDepositPayTradeNo();
                Tenpay query = new Tenpay();
                query.setTransactionId(payTradeNo);

                Tenpay tenpay = tenpayService.selectOne(dbKey, query);
                if (tenpay != null) {
                    WxMpService wxMpService = new WxMpServiceImpl();
                    Double totalFee = tenpay.getTotalFee() * 100;
                    int fee = totalFee.intValue();
                    RefundResData refundResData = wxMpService.refund(tenpay.getOutTradeNo(), tenpay.getTransactionId(), "", "", fee, fee, tenpay.getFeeType());

                    refundSucceed = refundResData.isResultSuccess();
                }
                refundStatus = refundSucceed ? TripRefundStatus.SUCCEESS
                        .getValue() : TripRefundStatus.FAILED.getValue();

            }// 支付宝支付
            else if (trip.getDepositPayId() == PayType.Alipay.getId()) {
                // 新的支付宝退款流程：直接调接口退款
                String payTradeNo = trip.getDepositPayTradeNo();
                Alipay query = new Alipay();
                query.setTradeNo(payTradeNo);

                Alipay alipay = alipayService.selectOne(dbKey, query);
                if (alipay != null) {
                    refundSucceed = AlipayCore.refund(alipay.getOutTradeNo(), alipay.getTradeNo(), alipay.getTotalFee().floatValue(), "user cancel order refund", "", "", "", "");
                    refundStatus = refundSucceed ? TripRefundStatus.SUCCEESS
                            .getValue() : TripRefundStatus.FAILED.getValue();
                }
                logger.error("userCancelTask.alipay::refundSucceed" + refundSucceed + ",refundStatus=" + refundStatus);

            }
            TripRefundRecord refundRecord = new TripRefundRecord();
            refundRecord.setTaskNo(tripNo);
            refundRecord.setRefundFee(trip.getDepositPayFee());
            refundRecord.setTaskPayId(trip.getDepositPayId());
            refundRecord.setTaskPayTradeNo(trip.getDepositPayTradeNo());
            refundRecord.setRefundStatus(refundStatus);
            refundRecord.setRefundTime(SystemUtil.getAllSeconds());
            // 设置备注为平台资金流动用途
            refundRecord.setRemark(FlowPurpose.TRIP_EXPIRED.getName());
            // 添加任务退款记录
            tripRefundRecordService.insert(dbKey, refundRecord);

            // 退款成功后添加平台资金流动记录,支付宝的再后台处理后在添加这个记录
            if (refundSucceed) {
                PlatformFundFlowRecord flowRecord = new PlatformFundFlowRecord();
                flowRecord.setRecordNo(SystemUtil.generateRandomNo(""));
                flowRecord.setUserUniqueId(trip.getOpenId());
                flowRecord.setUserType(PlatformUserType.CLIENT_USER.getValue());
                flowRecord.setFlowAmount(trip.getDepositPayFee());
                flowRecord.setInOut(FlowInOut.OUT.getValue());
                flowRecord.setFlowFrom("平台" + trip.getDepositPayName());
                flowRecord.setFlowTo("用户" + trip.getDepositPayName());
                flowRecord.setFlowMode(trip.getDepositPayId());
                flowRecord.setLinkNo(tripNo);
                flowRecord.setPurpose(FlowPurpose.TRIP_EXPIRED.getName());
                flowRecord.setRemark("行程过期，用户支付定金退还给用户");

                platformFundFlowRecordService.insert(dbKey, flowRecord);
            }
        }*/
        if (row > 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //用户行程单号
                    String serviceCode = trip.getServiceCode();
                    String moduleName = CustomMsgModule.getModuleName(serviceCode);
                    List<String> aliasList = new ArrayList<String>();
                    aliasList.add(trip.getOpenId());
                    String toUser = trip.getOpenId();
                    String message = String.format("你的%s行程已过期", moduleName);
                    String content = String.format("你的[%s]行程已过期,行程单号为：%s", moduleName, tripNo);
                    PushCustomMsg customMsg = new PushCustomMsg();
                    customMsg.setModule(serviceCode);
                    customMsg.setType(CustomMsgType.TripExpired.getValue());
                    customMsg.setKey(tripNo);

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setContent(content);
                    pushMessage.setModule(serviceCode);
                    pushMessage.setTitle(message);
                    pushMessage.setTripNo(trip.getTripNo());
                    pushMessage.setToUser(toUser);
                    pushMessage.setMessage(message);
                    pushMessage.setContent(content);
                    pushMessage.setExtras(customMsg.toJson());
                    pushMessage.setPushTime(SystemUtil.getAllSeconds());
                    pushMessage.setJumpUrl("");

                    pushMessageService.pushToUser(dbKey, pushMessage, PushTargetApp.Client, customMsg, aliasList, true);
                }
            }).start();
        }
        return row > 0;
    }


    @Override
    public Boolean timerMatchTrip(String dbKey, final ServiceTrip userTrip)
            throws Exception {
        try {
            Boolean systemAutoAssignTrip = dictService.getSystemAutoAssignTrip(dbKey);
            //系统自动派单开启
            if (systemAutoAssignTrip) {
                final String serviceCode = userTrip.getServiceCode();
                if (ServiceCode.BC.getCode().equals(serviceCode)) {
                    bcTripTread.setUserTrip(userTrip);
                    new Thread(bcTripTread).start();
                } else if (ServiceCode.ZC.getCode().equals(serviceCode)) {
                    zxpcTripThread.setUserTrip(userTrip);
                    new Thread(zxpcTripThread).start();
                } else if (ServiceCode.KC.getCode().equals(serviceCode)) {
                    kcTripThread.setUserTrip(userTrip);
                    new Thread(kcTripThread).start();

                } else if (ServiceCode.SFC.getCode().equals(serviceCode)) {
                    sfcTripThread.setUserTrip(userTrip);
                    new Thread(sfcTripThread).start();
                }
            }
            return true;
        } catch (Exception e) {
            throw e;
        }
    }
}
